Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.

Similar presentations


Presentation on theme: "Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3."— Presentation transcript:

1 Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3

2 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

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

4 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

5 Fall 2007CS 2255

6 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

7 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

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

9 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

10 Fall 2007CS 22510 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

11 Fall 2007CS 22511 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

12 Fall 2007CS 22512 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)

13 Fall 2007CS 22513 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

14 Fall 2007CS 22514 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();

15 Fall 2007CS 22515 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

16 Fall 2007CS 22516 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

17 Fall 2007CS 22517 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

18 Fall 2007CS 22518 Abstract Class Number and the Java Wrapper Classes

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

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

21 Fall 2007CS 22521 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

22 Fall 2007CS 22522 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

23 Fall 2007CS 22523 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

24 Fall 2007CS 22524 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

25 Fall 2007CS 22525 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

26 Fall 2007CS 22526 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”

27 Fall 2007CS 22527 The Shallow Copy Problem

28 Fall 2007CS 22528 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

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

30 Fall 2007CS 22530 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

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

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

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

34 Fall 2007CS 22534 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

35 Fall 2007CS 22535 Multiple Interfaces to Emulate Multiple Inheritance

36 Fall 2007CS 22536 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

37 Fall 2007CS 22537 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

38 Fall 2007CS 22538 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

39 Fall 2007CS 22539 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

40 Fall 2007CS 22540 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

41 Fall 2007CS 22541 Visibility Summary

42 Fall 2007CS 22542 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

43 Fall 2007CS 22543 A Shape Class Hierarchy

44 Fall 2007CS 22544 Rectangle Members

45 Fall 2007CS 22545

46 Fall 2007CS 22546 Shape Classes

47 Fall 2007CS 22547 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

48 Fall 2007CS 22548 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

49 Fall 2007CS 22549 Object Factory


Download ppt "Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3."

Similar presentations


Ads by Google