250 likes | 390 Views
Object-oriented Programming. Overview The inheritance relationship: is-a Method overriding Visibility Modifiers Polymorphism and dynamic method binding The keyword super Variable shadowing Constructors under inheritance Single implementation inheritance
E N D
Object-oriented Programming • Overview • The inheritance relationship: is-a • Method overriding • Visibility Modifiers • Polymorphism and dynamic method binding • The keyword super • Variable shadowing • Constructors under inheritance • Single implementation inheritance • Multiple interface inheritance and supertypes • Assigning, and casting references • The instanceof operator Inheritance (c) Eraj Basnayake
What is “inheritance”? Inheritance (c) Eraj Basnayake
Inheritance Natural, hierarchical way of organizing things. (superclass) Animal (subclasses of Animal) Dog Cat Biped (subclass of … ) Retriever Guard Lion Tiger Human (subclass of… ) Labrador German Shepherd Think in terms of “is a” relationships: A Lion is a Cat, and so is a Tiger A Labrador is a Retriever is a Dog is a Animal A Human is a(n) Biped is a Animal. Inheritance (c) Eraj Basnayake
Another hierarchy Light Artificial Light Natural Light Light Bulb Tube Light SpotLight Bulb NeonLight • Inheritance defines the relationship is-a (also called superclass-subclass • relationship) between a superclass and a subclass. • Classes higher up are more generalized as they abstract the class behavior. • Classes lower down are more specialized as they customize the inherited • (abstract) behavior using additional properties and behavior. Inheritance (c) Eraj Basnayake
Inheritance - Overview Class A • Class B inherits from Class A, or • Class B extends Class A • Class A is the more general form while Class B is a specialization. Class B Class B contains: • All of the properties of A • Its own methods, not found in A (EXTENDING class A) • Methods of A that were redefined in B. (OVERRIDING) Class A Class B must belong to the same family as A. You must be able to say: “B is a A” Inheritance (c) Eraj Basnayake
The Java Object class java.lang.Object attributes? clone() equals() finalize() toString() getClass() … Light Staff Member Attributes Attributes methods inherited from Object + its own methods inherited from Object + its own methods All classes in Java Inherit from the Object class Any object is-a(n) Object The Object class is always the root of any inheritance hierarchy Inheritance (c) Eraj Basnayake
A simple example of Inheritance java.lang.Object attributes? clone() equals() finalize() public String toString() public Class getClass() … Reason possible Foo f = new Foo(); System.out.println(f.getClass()); System.out.println(f.toString()); inheritance overriding Java console java.lang.Foo this is foo public class Foo{ public String toString(){ return “this is foo”; } } UML notation for inheritance between classes. The arrow originates at the class that is inheriting (the child). Inheritance (c) Eraj Basnayake
Method Overriding If a class, referred to as Child, inherits from another class, referred to as Parent, and if the Parent has a non-static,non-private, non-final method and the Child also has an identical method, then the Child’s method will replace (Override) that of the Parent in a Child object. This characteristic of replacing is called Method Overriding. public class Test{ public … main(String[] args){ Child c = new Child(); c.foo(); } } public class Parent{ public void foo(){ System.out.println(“I am a parent”); } } public class Child extends Parent{ public void foo(){ System.out.println(“I am a child”); } } Reason Method Overriding Output I am a child Warning: Don’t get Overriding and Overloading mixed up! Inheritance (c) Eraj Basnayake
Method Overriding… • A subclass may override non-static, non-private, and non-final methods inherited • from a superclass. (So that also means that any static, private, or final method • cannot be overridden by a subclass.) • When a method is invoked on an object of the subclass, it is the new method • definition in the subclass that is executed. • The new method definition in the subclass must have the same method • signature(i.e. method name and parameters), and the same return. • The new definition cannot “narrow” the accessibility of the method, but it • can widen it. • The new method definition can only specify all or a subset of the exception • classes specified by the throws clause of the overridden method. • A subclass can use the keyword super to invoke an overridden method in the • superclass. Inheritance (c) Eraj Basnayake
Overriding verses Overloading - what's the difference? • Method overriding requires the same method signature, the same return type • and the original method was inherited from its superclass. • Overloading requires different method signatures, but the method name should • be the same. • (To overload, the parameters must be different in type and/or number. The • return type is not a part of the signature, changing it is not enough to • overload methods.) • A method can be overloaded in the class it is defined in, or in a subclass. • To invoke an overridden method in the superclass from a subclass, requires the • use of super. Inheritance (c) Eraj Basnayake
Visibility Modifiers public A method/variable that is public is callable/accessible from within and out side of the current object private A method/variable that is private is callable/accessible from only within the current object only. protected A method or variable that is protected is accessible from within the objects of the current class and from within objects of subclasses provided the subclass does not override or shadow. Protected methods/variables cannot be called/accessed from outside the current or subclass. protected variables/methods are similar to private variables/methods from the clients perspective. Anything designated private cannot be inherited. Items designated private are accessible only within objects of that class only. Inheritance (c) Eraj Basnayake
Visibility Modifiers ... public class Parent{ protected int a; private int b; public int c; protected void pMethod1(){ System.out.println(“Parent:method1”); } private void pMethod2(){ System.out.println(“Parent:method2”); } public void pMethod3(){ method2(); method1(); } } public class Child extends Parent{ public void cMethod1(){ pMethod1(); pMethod2(); pMethod3(); } } public class Client{ public static void main(…) Child c = new Child(); c.cMethod1(); c.pMethod1(); c.pMethod2(); c.pMethod3(); } } A child’s method that overrides a parent method cannot narrow the methods visibility public method protected method - no client access private method - no client access public method - public access Inheritance (c) Eraj Basnayake
Example Animal Dog Cat Biped • Want to model relationships between the following classes: • Animal • Cat • Dog • Biped • Lets assume that all of these objects have • have a name • make a sound • and perform in some fashion Inheritance relationship: Design goals: • Group common properties high in the inheritance hierarchy so that all • sub classes inherit these. • Even if implementation is unknown, include method stubs high in the • inheritance hierarchy so that sub classes can inherit and override these. Inheritance (c) Eraj Basnayake
Example … class Animal { protected String strName = “”; protected String strNoise = “”; protected int iNumTimesPerformed = 0; protected static int population = 0; //assume constructors public void setName(String strName){ this.strName = strName; } public String getName(){ return strName; } public void setNoise(String noise){…} … public void identifySelf( ) { System.out.println(“My name is “ + strName); } // of identifySelf public void perform ( ) { doYourThing( ); iNumTimesPerformed++; } // of perform public void doYourThing( ) { ; // ‘no-op’ method } // of doYourThing } // of Animal So, animals have a name and noise and they can identify themselves, perform and do their thing. Animal harpo = new Animal(); harpo.setName(“Harpo”); harpo.doYourThing(); // says nothing Inheritance (c) Eraj Basnayake
Example … Animal Dog Cat Biped Subclasses (Dog extends Animal i.e. “A dog is an animal” or “All dogs are animals”) class Dog extends Animal { public Dog() { strNoise = “Woof”; } // of constructor public void doYourThing ( ) { identifySelf(); System.out.println(“I am a dog”); System.out.println(strNoise); } // of doYourThing } // of Dog Recall: The Animal class had a no-op method for doYourThing() Dog pickles = new Dog(); pickles.setName(“Pickles”); pickles.doYourThing(); // output: // “My name is Pickles” // “I am a dog” // “Woof” Inheritance (c) Eraj Basnayake
Example … Animal Dog Cat Biped Subclasses (Cat extends Animal i.e. “A cat is an animal” or “All cats are animals”) class Cat extends Animal { public Cat() { strNoise = “Miaow”; } // of constructor public void doYourThing ( ) { identifySelf(); System.out.println(“I am a cat”); System.out.println(strNoise); } // of doYourThing } // of Cat Cat abby = new Cat(); abby.setName(“Abby”); abby.doYourThing(); // output: // “My name is Abby” // “I am a cat” // “Miaow” Inheritance (c) Eraj Basnayake
Example … Animal Dog Cat Biped Subclasses (Biped extends Animal i.e. “A Biped is an animal” or “All Bipeds are animals”) class Biped extends Animal { public Biped() { strNoise = “I walk on two legs therefore I am”; } // of constructor public void doYourThing ( ) { identifySelf(); System.out.println(“I walk upright”); System.out.println(strNoise); } // of doYourThing } // of Human Biped descartes = new Biped(); Biped.setName(“Rene”); descartes.doYourThing(); // output: // “My name is Rene” // “I walk upright” // “I walk on two legs therefore I am” Inheritance (c) Eraj Basnayake
Inheritance and Scope • Variables (e.g. strNoise): • First examines current method, looks for local variable or parameter; • Then examines current class (e.g. Dog); • Then examines superclass (e.g. Animal); • Continues up the class hierarchy until no more superclasses to examine. • Methods (e.g. doYourThing() or identifySelf()): • First examines current class; • Then examines superclass; • Continues up inheritance hierarchy until no more superclasses to examine. Inheritance (c) Eraj Basnayake
Polymorphism and Dynamic method Binding “An object of a subclass can be used wherever an object of the superclass can be used.” Example: An object of TubeLight can be used whenever an object of the superclass, Light, can be used, since TubeLight is-a Light What does this mean? Light l; TubeLight tl = new TubeLight(); l = tl; Why is this “reasonable”? Polymorphism and Dynamic Method Binding The ability of a superclass reference to denote objects of its own class and those of its subclasses at runtime is called polymorphism. The method invoked is dependent on the actual type of the object denoted by the reference at runtime. Inheritance (c) Eraj Basnayake
Polymorphism … Observe public class Parent{ protected int a; public Parent(){ a = 0; } public void doStuff(){ System.out.println(“Parent do stuff”); } public void parentOnlyMethod(){ System.out.println(“Parent only method”); } } • Both classes have a “doStuff” method • Both classes have methods that are • unique to them Part 1: What happens now? Reasoning Constructor method overriding Inherited Extending parent Client Code Child child = new Child(); child.doStuff(); child.parentOnlyMethod(); child.childOnlyMethod(); public class Child extends Parent{ protected int b; public Child (){ a = 0; } public void doStuff(){ System.out.println(“Child do stuff”); } public void childOnlyMethod(){ System.out.println(“Child only method”); } } Inheritance (c) Eraj Basnayake
Polymorphism … public class Parent{ protected int a; public Parent(){ a = 0; } public void doStuff(){ System.out.println(“Parent do stuff”); } public void parentOnlyMethod(){ System.out.println(“Parent only method”); } } Part 2: What happens now? Child child = new Child(); child.doStuff(); child.parentOnlyMethod(); child.childOnlyMethod(); Client Code Parent p = child; p.doStuff(); p.parentOnlyMethod(); p.childOnlyMethod(); child = (Child) p; Reasoning bc, Child is-a Parent- Polymorphism, Upcasting Method overriding Inheritance ERROR! Down Casting - Dangerous! public class Child extends Parent{ protected int b; public Child (){ a = 0; } public void doStuff(){ System.out.println(“Child do stuff”); } public void childOnlyMethod(){ System.out.println(“Child only method”); } } Inheritance (c) Eraj Basnayake
Polymorphism … • Parent p = child; (or Parent p = new Child();) is possible because of inheritance. the “Child” is a “Parent”. Therefor, a parent reference can reference a child object. This is also known as Upcasting. • p.doStuff(); Because of method overriding. The “doStuff” method is redefined in the “Child”. In order to get method overriding, the signature have to match. • p.parentOnlyMethod(); Because of inheritance. The subclass “Child” inherits the method “parentOnlyMethod()” • p.childOnlyMethod(); Not accessible through a Parent reference. Methods exclusively in the subclass cannot be accessed via a super class reference. Inheritance (c) Eraj Basnayake
Polymorphism … • child = (Child) p; Called Down casting. This requires an explicit cast. Why? Warning: May through a “ClassCastException” Inheritance (c) Eraj Basnayake
A second example - what’s the output? Reason through the statements java.lang.Object java.lang.String equals() getClass() notify() ... equals() substring() length() ... class client{ public static void main(String args[]){ String stringRef = new String(“Java”); //(1) System.out.println(“(2): “+stringRef.getClass()); //(2) System.out.println(“(3): “+stringRef.length()); //(3) Object objRef = stringRef; //(4) System.out.println(“(5): “+objRef.equals(“Java”)); //(5) System.out.println(“(6): “+objRef.getClass()); //(6) stringRef = (String) objRef; //(7) System.out.println(“(8): “+stringRef.equals(“C++”); //(8) System.out.println(“(9): “+objRef.length()); //(9) } } Reasoning (2): Inheritance (3): Extending/Local method (4): Up casting/Polymorphism (5): Overriding (6): Inheritance (8): Overriding (7): Down casting (9): Error! Output from the program (2): class java.lang.String (3): 4 (4): (5): true (6): class java.lang.String (7) (8): false (9): Inheritance (c) Eraj Basnayake
Implications of Inheritance • An object of a subclass can be used wherever an object of • the superclass can be used. • The inheritance relationship is Transitive: if class B extends • class A, and class C extends B, then C inherits from A via B • (An object of SpotLight is-a Light) • The is-a relationship does not hold between peer classes. • (A Dog is-NOT-a cat) • Litmus test for using inheritance: if B is a(n) A, then let • B inherit from A. Do not use inheritance unless all inherited behavior makes sense Inheritance (c) Eraj Basnayake