Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.

Slides:



Advertisements
Similar presentations
OOP: Inheritance By: Lamiaa Said.
Advertisements

CS 211 Inheritance AAA.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Inheritance and Class Hierarchies Chapter 3 Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2007.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Lists and the Collection Interface Review inheritance & collections.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Coming up: Inheritance
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Object-Oriented Programming: Polymorphism Chapter 10.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Data Structures and Algorithms
Week 4 Object-Oriented Programming (1): Inheritance
Computer Science II Exam 1 Review.
MSIS 670 Object-Oriented Software Engineering
Lecture 22 Inheritance Richard Gesick.
Presentation transcript:

Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3

Fall 2007CS 2252 Chapter Topics Inheritance and how it facilitates code reuse Polymorphism Abstract classes The Object class and its methods Method overriding Cloning and the difference between a true clone (deep copy) and a shallow copy

Fall 2007CS 2253 Chapter Topics (continued) Single versus multiple inheritance Interfaces and delegation to simulate multiple inheritance Object factory design pattern Packages and visibility

Fall 2007CS 2254 Inheritance and Class Hierarchies One advantage of OOP is that it enables programmers to reuse previously written code saved as classes All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes Inheritance in OOP is analogous to inheritance in humans Inheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another

Fall 2007CS 2255

Fall 2007CS 2256 Is-a Versus Has-a Relationships One misuse of inheritance is confusing the has-a relationship with the is-a relationship Inheritance is used to support an is-a relation ship –The keyword extends specifies that one class is a subclass of another If B extends A, B is-a A The has-a relationship means that one class has the second class as an attribute –An instance variable of a particular type T means the object has-a T

Fall 2007CS 2257 A Superclass and a Subclass Consider two classes: Computer and Laptop A laptop is a kind of computer and is therefore a subclass of computer

Fall 2007CS 2258 Where would you add Cost Battery Time to discharge Number of expansion slots Wireless card present

Fall 2007CS 2259 Initializing Superclass Data Private data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parameters If the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass –Initializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object

Fall 2007CS Protected Visibility Private data fields are not accessible to derived classes Protected visibility allows data fields to be accessed either by the class defining it or any subclass In general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields

Fall 2007CS Method Overriding If a derived class has a method found within its base class, that method will override the base class’s method The keyword super can be used to gain access to superclass methods overridden by the base class A subclass method must have the same return type as the corresponding superclass method

Fall 2007CS Method Overloading Method overloading: having multiple methods with the same name but different signatures in a class Constructors are often overloaded Example: –MyClass(int inputA, int inputB) –MyClass(int inputA, int inputB, double inputC)

Fall 2007CS Polymorphism A variable of a superclass type can reference an object of a subclass type Polymorphism means many forms or many shapes Polymorphism allows the JVM to determine which method to invoke at run time At compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time

Fall 2007CS Example Computer [] comp = new Computer[3]; comp[0] = new Computer( …); comp[1] = new LapTop( …); comp[2] = new Computer( …) for (int i=0; i<comp.length; i++) System.out.println( comp[i].getRamSize() + "\n" + comp[i].toString();

Fall 2007CS Interfaces An interface can declare methods but does not provide an implementation of those methods –Methods declared in an interface are called abstract methods Interfaces also allow polymorphism

Fall 2007CS Abstract Classes An abstract class can have abstract methods, data fields, and concrete methods Abstract class differs from a concrete class in that –it cannot be instantiated –it can declare abstract methods, which must be implemented in its subclasses

Fall 2007CS Abstract Classes and Interfaces Like an interface, an abstract class can’t be instantiated An abstract class can have constructors to initialize its data fields when a new subclass is created –Subclass uses super(…) to call the constructor May implement an interface but it doesn’t have to define all of the methods declared in the interface –Implementation is left to its subclasses

Fall 2007CS Abstract Class Number and the Java Wrapper Classes

Fall 2007CS Summary of Features of Actual Classes, Abstract Classes, and Interfaces

Fall 2007CS Class Object Object is the root of the class hierarchy All classes inherit the methods defined in class Object but may override them

Fall 2007CS The Method toString You should always override the toString method if you want to represent an object’s state If you do not override it, the toString method for class Object will return a string…just not the string you want or are expecting

Fall 2007CS Operations Determined by Type of Reference Variable A variable can reference an object whose type is a subclass of the variable type –The type of reference, not the type of the object referenced, determines what operations can be performed Java is strongly typed so the compiler needs to be able to verify that the type of the expression being assigned is compatible with the variable type

Fall 2007CS Casting in a Class Hierarchy Java provides casting to enable us to process an object referenced by one type through a reference variable of its actual type Casting does not change the object referenced; it creates an anonymous reference to that object Downcast: cast a higher type to a lower type The instanceof operator can be used to avoid ClassCastException errors You can downcast an interface reference to the specific implementation type

Fall 2007CS Java 5.0 Reduces Need for Casting Two new features that reduce the need for casting: –Autoboxing/unboxing –Generics Autoboxing/unboxing eases the conversion between a primitive type and its corresponding wrapper type

Fall 2007CS The Method Object.equals The Object.equals method has a parameter of type Object Compares two objects to determine whether they are equal You must override the equals method if you want to be able to compare two objects of a class

Fall 2007CS Assignment with Objects Assignment of one object reference to another creates two references to the same object You can change the object using either reference Will cause e1.name and e2.name both reference “Jim”

Fall 2007CS The Shallow Copy Problem

Fall 2007CS Cloning The purpose of cloning in object-oriented programming is analogous to cloning in biology –Create an independent copy of an object Initially, both objects will store the same information Since they are different objects, you can change one object without affecting the other

Fall 2007CS The statement e1.setAddressLine1("Room 224"); creates a new String object that is referenced by e1.address.line1 and e2.address.line1

Fall 2007CS The Object.clone method Java provides the Object.clone method to help solve the shallow copy problem The initial copy is a shallow copy as the current object’s data fields are copied To make a deep copy, you must create cloned copies of all components by invoking their respective clone methods

Fall 2007CS Cloning After e1.setAddressLine1("Room 224"); only e1.address.line1 references the new String object.

Fall 2007CS Employee.clone() public Object clone() { try { Employee cloned = (Employee) super.clone(); cloned.address = (Address)address.clone(); return cloned; } catch (CloneNotSupportedException ex){ throw new InternalError(); }

Fall 2007CS Address.clone() public Object clone() { try { Address cloned = (Address) super.clone(); return cloned; } catch (CloneNotSupportedException ex){ throw new InternalError(); }

Fall 2007CS Multiple Inheritance Multiple inheritance: the ability to extend more than one class Multiple inheritance is a language feature that is difficult to implement and can lead to ambiguity –Therefore, Java does not allow a class to extend more than one class

Fall 2007CS Multiple Interfaces to Emulate Multiple Inheritance

Fall 2007CS Delegation Allows reuse through composition by delegating responsibilities to a member object Object composition combines objects to get more complex behavior –composition uses has-a relationships

Fall 2007CS Reuse Through Delegation Delegation is used to reduce –duplication of modifications problems associated with version control –A method of one class accomplishes an operation by delegating it to a method of another class

Fall 2007CS Packages The Java API is organized into packages The package to which a class belongs is declared by the first statement in the file in which the class is defined using the keyword package followed by the package name All classes in the same package are stored in the same directory or folder All the classes in one folder must declare themselves to be in the same package Classes that are not part of a package may access only public members of classes in the package

Fall 2007CS Package Visibility There exists a default package –Files that do specify a package are considered part of the default package If you don’t declare packages, all of your packages belong to the same, default package Package visibility sits between private and protected Classes, data fields, and methods with package visibility are accessible to all other methods of the same package but are not accessible to methods outside of the package Classes, data fields, and methods that are declared protected are visible to all members of the package

Fall 2007CS Visibility Supports Encapsulation The rules for visibility control how encapsulation occurs in a Java program Private visibility is for members of a class that should not be accessible to anyone but the class, not even the classes that extend it Package visibility allows the developer of a library to shield classes and class members from classes outside the package Use of protected visibility allows the package developer to give control to other programmers who want to extend classes in the package

Fall 2007CS Visibility Summary

Fall 2007CS Case Study: Problem Statement We want to draw some standard geometric shapes on the screen –rectangle, circle, right triangle Each shape has properties –position on the screen –interior color –border color Methods for –area, perimeter

Fall 2007CS A Shape Class Hierarchy

Fall 2007CS Rectangle Members

Fall 2007CS 22545

Fall 2007CS Shape Classes

Fall 2007CS Design Patterns "descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context –Design Patterns: Elements of reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides

Fall 2007CS Object Factories An object factory is a method that creates instances of other classes Object factories are useful when: –The necessary parameters are not known or must be derived via computation –The appropriate implementation of an interface or abstract class should be selected as the result of some computation

Fall 2007CS Object Factory