12.07.2015 Views

Inheritance and Class Hierarchies

Inheritance and Class Hierarchies

Inheritance and Class Hierarchies

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A Superclass <strong>and</strong> a Subclass• Consider two classes: Computer <strong>and</strong> Laptop• A laptop is a kind of computer <strong>and</strong> is therefore asubclass of computer


Initializing Data Fields in aSubclass <strong>and</strong> the No-ParameterConstructor• Private data fields belonging to a base class must beinitialized by invoking the base class’s constructor withthe appropriate parameters• If the execution of any constructor in a subclass doesnot invoke a superclass constructor, Java automaticallyinvokes the no-parameter constructor for the superclass• Initializes that part of the object inherited from thesuperclass before the subclass starts to initialize itspart of the object


Protected Visibility for SuperclassData Fields• Private data fields are not accessible to derived classes• Protected visibility allows data fields to be accessedeither by the class defining it or any subclass• In general, it is better to use private visibility becausesubclasses may be written by different programmers<strong>and</strong> it is always good practice to restrict <strong>and</strong> controlaccess to the superclass data fields


Method Overriding• If a derived class has a method foundwithin its base class, that method willoverride the base class’s method• The keyword super can be used to gainaccess to superclass methodsoverridden by the base class• A subclass method must have the samereturn type as the correspondingsuperclass method


Method Overloading• Method overloading: having multiple methods with thesame name but different signatures in a class• Constructors are often overloaded• Example:• My<strong>Class</strong>(int inputA, int inputB)• My<strong>Class</strong>(int inputA, int inputB, double inputC)


Polymorphism• A variable of a superclass type can reference an objectof a subclass type• Polymorphism means many forms or many shapes• Polymorphism allows the JVM to determine whichmethod to invoke at run time• At compile time, the Java compiler can’t determine whattype of object a superclass may reference but it isknown at run time


Abstract <strong>Class</strong>es, Assignment, <strong>and</strong>Casting in a Hierarchy• An interface can declare methods but does not providean implementation of those methods• Methods declared in an interface are called abstractmethods• An abstract class can have abstract methods, datafields, <strong>and</strong> concrete methods• Abstract class differs from a concrete class in that• An abstract class cannot be instantiated• An abstract class can declare abstract methods,which must be implemented in its subclasses


Abstract <strong>Class</strong>es <strong>and</strong> Interfaces• Like an interface, an abstract class can’t be instantiated• An abstract class can have constructors to initialize itsdata fields when a new subclass is created• Subclass uses super(…) to call the constructor• May implement an interface but it doesn’t have to defineall of the methods declared in the interface• Implementation is left to its subclasses


Abstract <strong>Class</strong> Number <strong>and</strong> theJava Wrapper <strong>Class</strong>es


Summary of Features of Actual<strong>Class</strong>es, Abstract <strong>Class</strong>es, <strong>and</strong>Interfaces


<strong>Class</strong> Object, Casting <strong>and</strong> Cloning• Object is the root of the class hierarchy; every classhas Object as a superclass• All classes inherit the methods defined in class Objectbut may be overridden


The Method toString• You should always override the toString method if youwant to represent an object’s state• If you do not override it, the toString method for classObject will return a string…just not the string you wantor are expecting


Operations Determined by Type ofReference Variable• A variable can reference an object whose type is asubclass of the variable type• The type of reference, not the type of the objectreferenced, determines what operations can beperformed• Java is a strongly typed language so the compiler alwaysverifies that the type of the expression being assignedis compatible with the variable type


Casting in a <strong>Class</strong> Hierarchy• Java provides casting to enable us to process one objectreferenced by one type through a reference variable ofits actual type• Casting does not change the object referenced; itcreates an anonymous reference to that object• Downcast: cast a higher type to a lower type• The instanceof operator can guard against<strong>Class</strong>CastException errors• You can downcast an interface reference to the specificimplementation type


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 aprimitive type <strong>and</strong> its corresponding wrapper type


The Method Object.equals• The Object.equals method has a parameter of typeObject• Compares two objects to determine whether they areequal• You must override the equals method if you want to beable to compare two objects of a class


Cloning• The purpose of cloning in object-oriented programming isanalogous to cloning in biology• Create an independent copy of an object• Initially, both objects will store the same information• You can change one object without affecting the other• Will cause both e1.name <strong>and</strong> e2.name to reference “Jim”


The Shallow Copy Problem


• The statement e1.setAddressLine1("Room 224"); createsa new String object that is referenced bye1.address.line1 <strong>and</strong> e2.address.line1


The Object.clone method• Java provides the Object.clone method to help solve theshallow copy problem• The initial copy is a shallow copy as the current object’sdata fields are copied• To make a deep copy, you must create cloned copies ofall components by invoking their respective clonemethods


The Object.clone method(continued)• After e1.setAddressLine1("Room 224"); only e1.address.line1references the new String object.


Employee.clone()


Address.clone()


Multiple <strong>Inheritance</strong>, MultipleInterfaces, <strong>and</strong> Delegation• Multiple inheritance: the ability to extend more than oneclass• Multiple inheritance is a language feature that isdifficult to implement <strong>and</strong> can lead to ambiguity• Therefore, Java does not allow a class to extendmore than one class


Using Multiple Interfaces toEmulate Multiple <strong>Inheritance</strong>• If we define two interfaces, a class can implement both• Multiple interfaces emulate multiple inheritance


Using Multiple Interfaces toEmulate Multiple <strong>Inheritance</strong>(continued)


Implementing Reuse ThroughDelegation• You can reduce duplication of modifications <strong>and</strong> reduceproblems associated with version control through atechnique known as delegation• In delegation, a method of one class accomplishes anoperation by delegating it to a method of another class


Packages• The Java API is organized into packages• The package to which a class belongs is declared by thefirst statement in the file in which the class is definedusing the keyword package followed by the package name• All classes in the same package are stored in the samedirectory or folder• All the classes in one folder must declare themselves tobe in the same package• <strong>Class</strong>es that are not part of a package may access onlypublic members of classes in the package


The No-Package-DeclaredEnvironment <strong>and</strong> Package Visibility• There exists a default package• Files that do specify a package are considered partof the default package• If you don’t declare packages, all of your packagesbelong to the same, default package• Package visibility sits between private <strong>and</strong> protected• <strong>Class</strong>es, data fields, <strong>and</strong> methods with packagevisibility are accessible to all other methods ofthe same package but are not accessible tomethods outside of the package• <strong>Class</strong>es, data fields, <strong>and</strong> methods that aredeclared protected are visible to all members ofthe package


Visibility Supports Encapsulation• The rules for visibility control how encapsulation occursin a Java program• Private visibility is for members of a class that shouldnot be accessible to anyone but the class, not even theclasses that extend it• Package visibility allows the developer of a library toshield classes <strong>and</strong> class members from classes outsidethe package• Use of protected visibility allows the package developerto give control to other programmers who want toextend classes in the package


Table 3.3• Private Visibility• <strong>Class</strong>es : Applicable to inner classes. Accessible onlyto members of the class in which it is declared.• <strong>Class</strong> Members: Visible only within this class.• Default (or package) Visibility• <strong>Class</strong>es : Visible to classes in this package.• <strong>Class</strong> Members : Visible to classes in this package.• Protected Visibility• <strong>Class</strong>es : Applicable to inner classes. Visible toclasses in this package <strong>and</strong> to classes outside thepackage that extend the class in which it is declared.• <strong>Class</strong> Members : Visible to classes in this package <strong>and</strong>to classes outside the package that extend this class.• Public Visibility• <strong>Class</strong>es: Visible to all classes.• <strong>Class</strong> Members : Visible to all classes. The classdefining the member must also be public.


Visibility Supports Encapsulation(continued)


A Shape <strong>Class</strong> Hierarchy


A Shape <strong>Class</strong> Hierarchy(continued)


A Shape <strong>Class</strong> Hierarchy(continued)


Object Factories• An object factory is a method that creates instances ofother classes• Object factories are useful when:• The necessary parameters are not known or must bederived via computation• The appropriate implementation of an interface orabstract class should be selected as the result ofsome computation


Object Factories (continued)


Chapter Review• <strong>Inheritance</strong> <strong>and</strong> class hierarchies to capture the ideathat one thing may be a refinement or extension ofanother• Encapsulation <strong>and</strong> inheritance impose structure onobject abstractions• The keyword interface defines an interface• The keyword abstract defines an abstract class ormethod• Delegation gains some of the advantages of multipleinheritance• Visibility is influenced by the package in which a class isdeclared

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!