








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









CMCMSSCC 1 1331 1:: CChhaapptteerr 2 23 3 ((SSuupppplleemmeenntt)) InInhheerriittaannccee IIII
IInnhheerriittaannccee:: QQuuiicckk RReeccaapp
Recap :
Th Thee CCllaassss HHiieerraarrcchhyy aanndd OObbjjeecctt
Class inheritance defines a hierarchy:
There is a class at the top of the hierarchy, called Object. Every class is derived (either directly or indirectly) from Object.
OObbjjeecctt
The class Object has no instance variables, but defines the a number of methods. These include: toString( ) : returns a String representation of this object. equals( Object o ) : test for equality with another object o.
Every class you define can, and probably should, override these two methods with something that makes sense for your class.
Ea Earrllyy aanndd LLaattee BBiinnddiinngg
Consider the following example:
Faculty carol = new Faculty( "Carol Tuffteacher", "999-99-9999", 1995 ); Person p = carol; System.out.println( p.toString( ) );
Q : Should this call Person’s toString or Faculty’s toString?
A : There are good arguments for either choice:
Early (static) binding : The variable p is declared to be of type Person. Therefore, we should call the Person’s toString. Late (dynamic) binding : The object to which p refers was created as a “new Faculty ”. Therefore, we should call the Faculty’s toString. Pros and cons : Early binding is more efficient, since the decision can be made at compile time. Late binding provides more flexibility.
Java uses late binding (by default) : so Faculty toString is called. (Note: C++ uses early binding by default.)
Disabling Overriding with “final”
final : Has two meanings, depending on context:
Po Pollyymmoorrpphhiissmm aanndd AAbbssttrraacctt MMeetthhooddss
Polymorphism : is allows us to write generic methods that leave the low-level details for the subclasses to implement.
Example : Typical graphics drawing program.
PoPollyymmoorrpphhiissmm aanndd AAbbssttrraacctt MMeetthhooddss
Example : Graphics drawing program.
Po Pollyymmoorrpphhiissmm aanndd AAbbssttrraacctt MMeetthhooddss
Problem : The Shape object does not represent a specific shape. So how do we implement Shape’s drawMe( ) method?
Better solution : Abstract methods/classes
Abstract Method : a method that contains no body. It is just a placeholder. The derived classes will provide the actual implementation.
InInhheerriittaannccee:: YYeett AAnnootthheerr QQuuiicckk RReeccaapp
Recap :
ggeettCCllaassss aanndd iinnssttaanncceeooff
Objects in Java can access there type information dynamically.
getClass( ) : Returns a representation of the class of any object.
Person bob = new Person( … ); Person ted = new Student( … ); if ( bob.getClass( ) == ted.getClass( ) ) // false (ted is really a Student) instanceof : You can determine whether one object is an instance of (e.g., derived from) some class using instanceof. Note that it is a operator (!) in Java, and not a method call. // true // true // true // false
// true // Illegal! Doesn’t compile
if ( bob instanceof Person ) if ( ted instanceof Student ) if ( ted instanceof Person ) if ( bob instanceof Student ) Faculty carol = new Faculty( … ); if ( carol instanceof Person ) if ( carol instanceof Student )
UpUp--ccaassttiinngg aanndd DDoowwnn--ccaassttiinngg
We have already seen that we can assign a derived class reference anywhere that a base class is expected. Upcasting : Casting a reference to a base class (casting up the inheritance tree). This is done automatically and is always safe. Downcasting : Casting a reference to a derived class. This may not be legal (depending on the actual object type). You can force it by performing an explicit cast.
Person bob = new Person( … ); Person ted = new Student( … ); Student carol = new Student( … ); GradStudent alice = new GradStudent( … ); // okay: ted is a Person // compile error! ted may not be a Student // okay: ted is a Student // run-time error! ted isn’t a GradStudent
bob = ted; carol = ted; carol = ( Student ) ted; alice = ( GradStudent ) ted;
SSaaffee DDoowwnnccaassttiinngg
Illegal downcasting results in a ClassCastException run-time error.
Q : Can we check for the legality of a cast before trying it?
A : Yes, using instanceof.
Example : Suppose that we want to store a list of university people references an ArrayList. We then want to print the GPA’s of all the students.
Recall : the following ArrayList methods:
int size( ) : Returns the size of the list. void add( Object x ) : Adds x to the end of the list. Object get( int i ) : Returns a reference to the object at position i.
As elements are removed from the list they must be downcast from Object to Student , but this can only be done if the object really is a Student.
eqequuaallss:: TThhee RRiigghhtt WWaayy
Example : Write a method that looks up a person (Person, Student, or Faculty) in an ArrayList containing university person objects. public static boolean find( Person p, ArrayList list ) { for ( int i = 0; i < list.size( ); i++ ) { if ( p.equals ( list.get( i ) ) ) return true; } return false; }
Suppose that we have : Person p = new Student( … ); find( p, list); Which equals method will be called here? Person equals( )? p is declared to be type Person Student equals( )? Late binding uses actual object type (Student) Object equals( )? ArrayList.get( ) returns an Object reference
eq equuaallss:: TThhee RRiigghhtt WWaayy
Answer : Object equals( ) is called (Surprise!)
Huh? Isn’t this a case of method overriding? Since p is a Student, we should call Student equals?
What are Java’s options?
All of these methods take different parameter types.
Java selects the option that best matches the parameter type, which is Object. So Object equals( ) is called.
eqequuaallss:: TThhee RRiigghhtt WWaayy
What is the right way to define equals? It should:
Co Coppyyiinngg aanndd IInnhheerriittaannccee
We have seen how to make copies of objects using the copy constructor:
Student amy = new Student( "Amy", "555", 3002, 3.5 ); Student amyCopy = new Student( amy ); public Student( Student s ) { super( s ); admitYear = s.admitYear; gpa = s.gpa; }
As with equals, we will run into problems if we try to use this to copy other types of Person objects , but the problems are of a different nature here.
CoCoppyyiinngg:: TThhee RRiigghhtt WWaayy
Solution : We use inheritance and method overriding , so Java will call the correct copying method.
clone :
public static Person[ ] goodCopy( Person[ ] list ) { Person[ ] list2 = new Person[ list.length ]; for ( int i = 0; i < list.length; i++ ) { list2[i] = ( Person ) list[i].clone( ); } return list2; }
De Deffiinniinngg CClloonnee
How to define clone?
SuSummmmaarryy ooff eeqquuaallss aanndd cclloonnee
General Warning: