Lecture#07
Inheritance & Method Overriding
Course: Object oriented Programming (CE-205)
Course Teacher: Dr Umm-e-Laila& Ms.Aneeta Siddiqui
Contact Info:
Room No: BS-04, CED
1 Email: ulaila@ssuet.edu.pk
Course Books
Text Book:
Herbert Schildt, Java: The Complete Reference, 12th
Edition ,McGraw-Hill Education.
Deitel, Paul, Java How to Program, 11th Edition, Pearson,
2017
Reference Books:
Horton, Ivor, Beginning Java, 7th Edition, Wrox, 2011
2
Course Instructors
Dr. Umm-e-Laila ulaila@ssuet.edu.pk
Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536
Aneeta Siddiqui aarshad@ssuet.edu.pk
Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Marks Distribution
Assignments + Quiz ______________
20
Mid Term ______________
30
Semester Final Paper ______________
4
50
Topics Covered
Inheritance
Method Overriding with example
5
6 Inheritance
Inheritance in java involves a relationship between
parent and child classes.
The process by which one class acquires the
properties(data members) and
functionalities(methods) of another class is called
inheritance.
7 Inheritance
The aim of inheritance is to provide the
reusability of code so that a class has to write
only the unique features and rest of the
common properties and functionalities can
be extended from the another class.
8 Inheritance
Child Class:
The class that extends the features of another
class is known as child class, sub class or derived
class( implementation inheritance)
In Java, implementation inheritance is achieved
by extending classes
Parent Class:
The class whose properties and functionalities are
used(inherited) by another class is known as
parent class, super class or Base class.
Inheritance Hierarchy
Object
Class Animal
Class Cat Class Dog Class Duck
Class spaniel
Inheritance Hierarchy
Classes higher up in the hierarchy are more generalized, as
they abstract the class behavior.
Classes lower down in the hierarchy are more specialized, as
they customize the inherited behavior by additional properties
and behavior
Inheritance defines the relationship is-a (also called the
superclass–subclass relationship) between a superclass and
its subclasses.
This means that an object of a subclass can be used wherever
an object of the superclass can be used
A class in Java can only extend one other class; that is, it can
only have one immediate superclass. This kind of inheritance is
sometimes called single or linear implementation
inheritance.
An object of the Dog class is-an object of the superclass Animal
inheritance relationship is transitive: if class B extends class A,
then a class C, which extends class B, will also inherit from class
A via class B.
The is-a relationship does not hold between peer classes.
11
Inheritance
# Example 01
class ParentClass{
public int parentVariable = 10;
public void parentFunction()
{ System.out.println( "Parent Function" ); }
}
class ChildClass extends ParentClass{
public void childFunction() {
parentFunction();
System.out.println( "In Child " + parentVariable ); }
}
}
public static void main(String args[]){
//Creating the object of child class
ChildClass example = new ChildClass();
example.childFunction();
example.parentFunction();
System.out.println( example.parentVariable ); }
}
}
12 Inheritance
# Example 01
Output:
Parent Function
In Child 10
Parent Function 10
13 SuperClass Members
Inheritance of members is closely tied to
their declared accessibility.
If a superclass member is accessible by
its simple name in the subclass (without
the use of any extra syntax like super),
then that member is considered
inherited.
private, overridden, and hidden
members of the superclass are not
inherited
If no extends clause is specified in the
header of a class declaration, then the
class implicitly inherits from the
java.lang.Object class.
Important Points
Note that constructors are not members and
are not inherited by subclasses.
The following list itemizes the members that are
inherited by a subclass:
1. Subclasses inherit those superclass members declared as
public or protected.
2. Subclasses inherit those superclass members declared
with no access specifier as long as the subclass is in the
same package as the superclass.
3. Subclasses don't inherit a superclass's member if the
subclass declares a member with the same name. In the
case of member variables, the member variable in the
subclass hides the one in the superclass. In the case of
methods, the method in the subclass overrides the one in
the superclass
15 Advantage of Inheritance
Inheritance allows us to reuse of code, it improves reusability in your
java application.
Note: The biggest advantage of Inheritance is that the code that is
already present in base class need not be rewritten in the child class.
16 Method Overriding
Declaring a method in sub class which is already
present in parent class is known as method
overriding.
Overriding is done so that a child class can give its
own implementation to a method which is already
provided by the parent class.
In this case the method in parent class is called
overridden method and the method in child class
is called overriding method.
The method that will be executed depends on the
object.
Overriding and Hiding Members
Instance Method Overriding
a subclass may override non-static methods methods
defined in the superclass .
When the method is invoked on an object of the
subclass, it is the new method implementation in the
subclass that is executed.
The overridden method in the superclass is not inherited
by the subclass, and the new method in the subclass
must uphold the following rules of method overriding:
Method Overriding rules
1. The new method definition must have the same
method signature (i.e., method name and
parameters) and the same return type.
2. A subclass cannot override methods that are
declared final in the superclass (by definition,
final methods cannot be overridden). If you
attempt to override a final method, the compiler
displays an error message.
3. Whether parameters in the overriding method
should be final is at the discretion of the subclass A
method's signature does not encompass the
final modifier of parameters, only their types
and order.
4. The new method definition cannot narrow the
accessibility of the method, but it can widen it
5. Constructors cannot be overridden.
6. Accessibility modifier private for a method means
that the method is not accessible outside the class
in which it is defined; therefore, a subclass cannot
override it.
19 Method Overriding
# Example 01
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
20 Method Overriding
# Example 01
Output:
Boy is eating
21 Method Overriding
# Example 02
This is called
class Animals{
public void sound(){
overriding a method
System.out.println("This is parent class."); Method sound in
}
} Dog overrides
class Dogs extends Animals{ method sound in
public void sound(){
System.out.println("Dogs bark");
Animal
} A subclass variable
}
class m{ can shadow a
public static void main(String[] args){ superclass variable,
Dogs d = new Dogs();
d.sound();
but a subclass
} method can override
} a superclass method
22 Method Overriding
# Example 02 cont..
Output:
Dogs bark
23 Methods a Subclass Must Override
A subclass must override methods that
are declared abstract in the superclass,
or the subclass itself must be abstract.
an abstract method requires the non-
abstract subclasses to override the
method, in order to provide an
implementation.
24 Why override a method?
Dog dog = new Dog();
System.out.println(dog);
Prints something like Dog@feda4c00
The println method calls the toString method, which is defined in
Java’s top-level Object class
Hence, every object can be printed (though it might not look pretty)
Java’s method public String toString() can be overridden
If you add to class Dog the following:
public String toString() {
return name;
}
Then System.out.println(dog); will print the dog’s name, which may be
something like: Fido
25 More about toString()
It is almost always a good idea to override
public String toString()
to return something “meaningful” about the object
When debugging, it helps to be able to print objects
When you print objects with System.out.print or
System.out.println, they automatically call the objects
toString() method
When you concatenate an object with a string, the
object’s toString() method is automatically called
You can explicitly call an object’s toString() method
26 Equality
Consider these two assignments:
Thing thing1 = new Thing();
Thing thing2 = new Thing();
Are these two “Things” equal?
That’s up to the programmer!
But consider:
Thing thing3 = new Thing();
Thing thing4 = thing3;
Are these two “Things” equal?
Yes, because they are the same Thing!
27
The equals method
Primitives can always be tested for equality with ==
For objects, == tests whether the two are the same object
Two strings "abc" and "abc" may or may not be == !
Objects can be tested with the method
public boolean equals(Object o)
in java.lang.
Unless overridden, this method just uses ==
It is overridden in the class String
It is not overridden for arrays; == tests if its operands are the same
array
Morals:
Never use == to test equality of Strings or arrays or other objects
Use equals for Strings, java. util.Arrays.equals(a1, a2) for arrays
If you test your own objects for equality, override equals
28 Calling an overridden method
When your class overrides an inherited method, it
basically “hides” the inherited method
Within this class (but not from a different class),
you can still call the overridden method, by
prefixing the call with super.
Example: super.printEverything();
You would most likely do this in order to observe
the DRY principle
The superclass method will do most of the work, but you
add to it or adjust its results
This isn’t a call to a constructor, and can occur anywhere
in your class (it doesn’t have to be first)
29 Super
A subclass must use the keyword super
in order to invoke an overridden
method in the superclass
Field Hiding
A subclass cannot override fields of the
superclass, but it can hide them.
The subclass can define fields with the same
name as in the superclass.
If this is the case, the fields in the superclass cannot be
accessed in the subclass by their simple names;
therefore, they are not inherited by the subclass.
Code in the subclass can use the keyword super
to access such members, including hidden fields.
A client can use a reference of the superclass to
access members that are hidden in the subclass if
the hidden field is static, it can also be accessed
by the superclass name.
When an instance method is invoked on an object
using a reference, it is the class of the current object
denoted by the reference, not the type of the
reference, that determines which method
implementation will be executed.
Inheritance: Field Hiding
31
# Example 03
class Parent{
public String name = "Parent";
public void parentPrint() {
System.out.println( name ); }
}
class Child extends Parent{
String name = "Child";
public void print() {
System.out.println( name ); }
}
public static void main(String args[]){
Child whoAmI = new Child();
whoAmI.print();
whoAmI.parentPrint();
System.out.println( whoAmI.name );
System.out.println( ( (Parent ) whoAmI).name );
}
}
32 Inheritance
# Example 03
Output:
1.Child
2.Parent
3.Child
4.Parent
Inheritance: Super keyword
33
# Example 04
class Parent{
public String name = "Parent";
}
class Child extends Parent{
String name = "Child";
public void print() {
System.out.println( name );
System.out.println( super.name );}
}
class GrandChild extend Child {
String name = "GrandChild"; }
class SuperMain {
public static void main(String args[]){
GrandChild whoAmI = new GrandChild();
whoAmI.print();
}
}
34 Inheritance
# Example 04
Output:
1.Child
2.Parent
Casting and Classes
An instance of a child class can be
assigned to a variable (field) of the
parent class.
If a variable references an object of a subclass, the object
can be cast down to its actual type with an explicit cast. The
explicit cast is required.
A runtime error occurs when explicitly casting an object to a
type that it is not hierarchy
In the code below the cast "(Uncle)
object" is a runtime error because at
that time object holds an instance of the
Child class, which is not of type (or
subclass) of Uncle. An object of type
Parent cannot be cast to type Child.
36 Casting and Classes
Inheritance: Casting
37
# Example 05
class Parent{
int data;
}
class Child extends Parent{
String name;
}
class Uncle {
String rich;
}
class Casting {
Object object;
Parent parent;
Child child = new Child();
Uncle uncle;
parent = child;
object = child;
parent = (Parent) object; // explicit cast down
child = (Child) object; // explicit cast down
uncle = (Uncle) object; //Runtime exception }
}
38 Inheritance
# Example 05
Output:
java.lang.ClassCastException: Child:
cannot cast to Uncle
Constructors and Inheritance
Before the constructor in a Child class is called, its
parent's constructor will be called
If the Child class constructor does not do this, the
parent's constructor with no arguments will be
implicitly called.
super( arg list) as the first line in a constructor
explicitly calls the parent's constructor with the
given signature If
1. Parent class implements a constructor with
arguments & Parent class does not implement
a constructor with no arguments
2. Then the Child constructors must eventually
explicitly call a parents constructor
40 Inheritance: Implicit Call to Parent
# Constructor
Example 06
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
}
class JavaExample extends ParentClass{
JavaExample(){
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
System.out.println("Constructor of Child");
}
public static void main(String args[]){
//Creating the object of child class
new JavaExample();
}
}
41 Inheritance
# Example 06
Output:
Constructor of Parent
Constructor of Child
42 Inheritance: Explicit Call to Parent
Constructor
# Example 07
class Parent{
//Parent class constructor
public Parent( ) {
System.out.println( "In Parent, No Argument" );
}
public Parent( String message ) {
System.out.println( "In Parent" + message );
}
}
class Child extends Parent {
//Child class constructor
public Child( String message, int value )
{ this( message ); // if occurs must be first
System.out.println( "In Child" ); }
public Child( String message )
{ super( message ); // if occurs must be first
System.out.println( "In Child" + message ); }
Class Constructors
public static void main(String args[]){
System.out.println( "Construct Child" );
Child care = new Child( ">Start from Child<", 5 ); }
}
43 Inheritance
# Example 07
Output:
In Parent>Start from Child<
In Child>Start from Child<
In Child
No Default Parent Constructor
The compiler will not generate the default
constructor for the class "Parent", since "Parent" has
a constructor. The class "Child" makes an implicit call
to the default constructor in "Parent". This causes a
compile error.
# Example 08
class Parent {
public Parent( String message )
{ System.out.println( "In Parent" + message ); }
}
class Child extends Parent {
public Child( ) { // Compile Error
System.out.println( "In Child" ); }
public Child( String message ) {
super( message );
System.out.println( "In Child" + message ); } }
Difference between Method
Overloading
and Method Overriding
S Method Overloading Method Overriding
#
1 Method overloading is Method overriding is used to
used to increase the provide the specific
readability of the implementation of the
program method that is already
provided by its super class.
2 Method overloading is Method overriding occurs in
performed within class. two classes that have IS-A
(inheritance) relationship.
3 In case of method In case of method overriding,
overloading, parameter parameter must be same.
must be different.
4 Method overloading is the Method overriding is the
example of compile time example of run time
polymorphism. polymorphism.
5 In java, method Return type must be same or
overloading can't be covariant in method
performed by changing overriding.
46 Task
Implement the following Hierarchy
47 Task
Summary
48
You should overload a method when you want to do
essentially the same thing, but with different parameters
You should override an inherited method if you want to
do something slightly different than in the superclass
It’s almost always a good idea to override public void
toString() -- it’s handy for debugging, and for many
other reasons
To test your own objects for equality, override public
void equals(Object o)
There are special methods (in java.util.Arrays) that you
can use for testing array equality
You should never intentionally shadow a variable