![Page 1: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/1.jpg)
InheritanceInheritance
![Page 2: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/2.jpg)
InheritanceInheritance
• Early programmers often wrote code very similar to existing code
• Example: A human resources system might handle different types of personnel. Much of the code for different classifications of personnel would be identical
• This was often handled by cutting and pasting code and then modifying
• Needed a way to capture and formalize the similarity
![Page 3: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/3.jpg)
InheritanceInheritance
Natural, hierarchical way of organizing things.
Staff Member
Employee Volunteer
Hourly Salaried
Consultant
Think in terms of “is a” relationships: An Employee is a Staff Member, as is a Volunteer. An Hourly worker is a(n) Employee. A Consultant is a(n) Hourly employee.
(subclass of Hourly)
(subclass of Employee)
(subclass of Staff)
(superclass)
![Page 4: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/4.jpg)
Classes and SubclassesClasses and Subclasses
class Animal {
public String name = ""; public String noise = ""; public int numTimesPerformed = 0;
// constructors, accessors & modifiers go here
public void identifySelf( ) { System.out.println(“My name is “ + name); } // of identifySelf
public void perform( ) { doYourThing( ); numTimesPerformed++; } // of perform
public void doYourThing( ) {; // ‘no-op’ method
} // of doYourThing } // of Animal
Don’t worry about“private” and “public” for now
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
![Page 5: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/5.jpg)
SubclassesSubclasses(Dog extends Animal
i.e. “A dog is an animal” or“All dogs are animals”)
class Dog extends Animal { public Dog() { noise = “Woof”; } // of constructor
public void doYourThing ( ) { identifySelf(); System.out.println(“I am a dog”); System.out.println(noise); } // 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”
Animal
Dog Cat Human
![Page 6: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/6.jpg)
SubclassesSubclasses(Cat extends Animal
i.e. “A cat is an animal” or“All cats are animals”)
class Cat extends Animal { public Cat() { noise = “Miaow”; } // of constructor
public void doYourThing ( ) { identifySelf(); System.out.println(“I am a cat”); System.out.println(noise); } // of doYourThing
} // of Cat
Cat abby = new Cat();abby.setName(“Abby”);abby.doYourThing();// output:// “My name is Abby”// “I am a cat”// “Miaow”
Animal
Dog Cat Human
![Page 7: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/7.jpg)
SubclassesSubclasses(Human extends Animal
i.e. “A human is an animal” or“All humans are animals”)
class Human extends Animal { public Human() { noise = “I think therefore I am”; } // of constructor
public void doYourThing ( ) { identifySelf(); System.out.println(“I am a sentient being”); System.out.println(noise); } // of doYourThing
} // of Human
Human descartes = new Human();descartes.setName(“Rene”);descartes.doYourThing();// output:// “My name is Rene”// “I am a sentient being”// “I think therefore I am”
Animal
Dog Cat Human
![Page 8: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/8.jpg)
Questions?Questions?
![Page 9: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/9.jpg)
Inheritance & ScopeInheritance & Scope
Using super & this
![Page 10: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/10.jpg)
Inheritance and ScopeInheritance and Scope
Variables (e.g. noise):• Java first examines current method, looks for local variable or parameter;• Java then examines current class (e.g. Dog);• Java then examines superclass (e.g. Animal); • Java continues up the class hierarchy until no more superclasses to examine.
Methods (e.g. doYourThing() or identifySelf()):• Java first examines current class;• Java then examines superclass;• Java continues up inheritance hierarchy until no more superclasses to examine.
![Page 11: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/11.jpg)
Specifying ScopeSpecifying Scope
Java allows you to override the scope rules by saying which variable/method you’re referring to:
Keyword super:keyword for specifying method or variable from superclass, e.g., super.doYourThing( )
Keyword this:keyword for specifying method or variable in current object, e.g., this.doYourThing( )
![Page 12: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/12.jpg)
Using super & thisUsing super & this
class Dog extends Animal { public Dog() { super.noise = “Woof”; } // of constructor
public void doYourThing ( ) { super.identifySelf(); System.out.println(“I am a dog”); System.out.println(noise); } // of doYourThing
} // of Dog
Same (in this case) asnoise = “Woof”;andthis.noise = “Woof”;
Animal
Dog Cat Human
Same (in this case) asidentifySelf();orthis.identifySelf();
(but why??)
![Page 13: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/13.jpg)
Using super and thisUsing super and this
class Animal {
String name;
}
class Dog extends Animal {
String name; /* Just so I don't forget! */
void twoNames() {
System.out.println
("My dog name is " + name);
System.out.println
("My animal name is " + super.name);
}
}
![Page 14: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/14.jpg)
Using superUsing super
class Dog extends Animal { // constructor as before
public void doYourThing() {identifySelf();System.out.println(noise);
} // of doYourThing
public void identifySelf() { super.identifySelf();
System.out.println(“I am a dog”); } // of identifySelf
} // of Dog
Animal
Dog Cat Human
I.e.this.identifySelf()(newly defined below)
I.e. theidentifySelf()(defined in Animal)
If omitted???
![Page 15: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/15.jpg)
class Shape {
public String name; public String getName () { return (this.name); } // getName
public int area () { return (0); } // area
} // Shape
A geometry exampleA geometry example
Shape
CircleRectangle
Each extending object would override the area() method.
![Page 16: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/16.jpg)
class Rectangle extends Shape { private int length, width; Rectangle () { this(0, 0); } // constructor
Rectangle (int l, int w) { this( l, w, “rectangle”); } // constructor
Rectangle (int l, int w, String n) { length = l; width = l; name = n; } // constructor
public int area () { return (length * width); } // area
public String getName () { if (length == width) return "square"; else return super.getName()); } // getName
public String toString () { String s; s = new String ("A " +
getName() + " with length " + length + " and width " + width);
return (s); } } // toString
} // Rectangle
Constructor “chaining”Constructor “chaining”
The Circle class implementation is left as an exercise to the reader.
![Page 17: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/17.jpg)
Java’s rule:
• If first line of constructor is not an explicit call to a superclass constructor, Java will implicitly put super( ) as the first line, calling the superclass default constructor.
public Dog() { strNoise = “Woof”; } // of constructor
• An exception to this rule: chained constructor call to this(params) will defer(ertelemek) super( ) call
• To use superclass constructors with params, call them explicitly, e.g., super(strName)
Constructors and InheritanceConstructors and Inheritance
implied call to Animal() here
![Page 18: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/18.jpg)
Look Closer...Look Closer...
class Rectangle extends Shape { private int length, width; Rectangle () { this(0, 0); } // constructor
Rectangle (int l, int w) { this( l, w, “rectangle”); } // constructor
Rectangle (int l, int w, String n) { length = l; width = l; name = n; } // constructor
public int area () { return (length * width); } // area
Shape();
What if there is no Shape()???
What if I want a Shape
constructor run here?
Error
![Page 19: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/19.jpg)
Inheritance and ScopingInheritance and Scoping
Examples:
super(xxx) // calls a superclass constructorsuper.xxx // accesses superclass’ variablesuper.xxx( ) // calls superclass’ method
this(xxx) // calls a current-class constructorthis.xxx // accesses current class’s variablethis.xxx( ) // calls current class’ method
Note: cannot do super.super<something>
(can achieve this effect via casting, but rarely should; details later...)
![Page 20: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/20.jpg)
Chaining, superclass exampleChaining, superclass example
![Page 21: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/21.jpg)
class Parent { String name; public Parent() { setName("NONE"); cp(1); } public Parent(String name) { setName(name); cp(2); } public void setName(String name) { this.name = name; cp(3); } public void cp(int n) { System.out.println("At checkpoint "+n+" "+name); } public static void main(String args[]) { Child c = new Child(); } } // Parentclass Child extends Parent { public Child() { this("NONAME"); cp(4); } public Child(String name) { this.name = name; cp(5); }} // Child
Output:At checkpoint 3 NONEAt checkpoint 1 NONEAt checkpoint 5 NONAMEAt checkpoint 4 NONAME
![Page 22: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/22.jpg)
class Parent { String name; public Parent() { setName("NONE"); cp(1); } public Parent(String name) { setName(name); cp(2); } public void setName(String name) { this.name = name; cp(3); } public void cp(int n) { System.out.println("At checkpoint "+n+" "+name); } public static void main(String args[]) { Child c = new Child("Bob"); } } // Parentclass Child extends Parent { public Child() { this("NONAME"); cp(4); } public Child(String name) { this.name = name; cp(5); }} // Child
Output:At checkpoint 3 NONEAt checkpoint 1 NONEAt checkpoint 5 Bob
![Page 23: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/23.jpg)
Recall: Class Recall: Class ObjectObject
• Java provides a base class, Object
• All classes that do not have an extends clause implicitly inherit directly from class java.lang.Object
Examples utilizing this fact:
public boolean equals (Object o);
public boolean String toString ();
• When you create your own toString( ) method for a class,
you are overridingoverriding the toString( ) provided by Object.
![Page 24: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/24.jpg)
Object HierarchyObject Hierarchy
Animal
Dog Cat Human
Object
Employee
Salaried Hourly
class Object methods: String toString() boolean equals(Object obj) and a few others...
Animal
Dog Cat Human
Object
Employee
Salaried Hourly
Or how about...
![Page 25: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/25.jpg)
Questions?Questions?
![Page 26: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/26.jpg)
Primitive types (e.g., int) are not classes
But sometimes, we may have need to make use of primitive types in a context that requires that we manipulate objects, not primitives
e.g. many collection classes are collections of Objects
Java provides a set of wrapper classes (a.k.a. type wrappers, a.k.a. envelope classes) to support treating primitives as objects.
It does this by providing a specific class that corresponds to each primitive data type
They are in java.lang, so the names are universally availableThe names are mostly identical to primitive types, but capitalized...
Wrapper ClassesWrapper Classes
![Page 27: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/27.jpg)
Wrapper ClassesWrapper Classes Class corresponds to Primitive
Boolean boolean Character char Byte byte Short short Integer int Long long Float float Double double
Each one:• allows us to manipulate primitives as objects• contains useful conversion methods.
E.g. Integer containsstatic Integer valueOf(String s)Integer.valueOf("27")is the object corresponding to int 27
• contains useful utility methods (e.g. for hashing)
![Page 28: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/28.jpg)
Using wrappers to bridge between objects and primitives:
// create and initialize an int int i = 7;
// create an Integer object and convert the int to it Integer intObject = new Integer( i );
// retrieve the int by unwrapping it from the object System.out.println( intObject.intValue() );
// convert a string into an Integer object String strS = "27"; Integer intObject intObject = new Integer (strS);
// then to an int int a = intObject.intValue(); // one way int b = Integer.parseInt(strS); // second way
Wrapper ClassesWrapper Classes
![Page 29: Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types](https://reader036.vdocument.in/reader036/viewer/2022070415/56649ebc5503460f94bc5720/html5/thumbnails/29.jpg)
Questions?Questions?