Unit 3 - Lecture-4
Unit 3 - Lecture-4
1
Unit-3
• Inheritance:
• Inheritance in Java,
• Types,
• Constructor in Inheritance,
• Using final with Inheritance,
• Accessing superclass member,
• Override private methods,
• Parent and Child classes having same data member,
• Base vs derived class reference.
• Polymorphism:
• Method Overloading,
• Overloading main(),
• Static vs Dynamic Binding,
• Method Hiding.
• Private and final methods,
• Passing and Returning Objects in Java
Hiding Fields & Methods
• Java, if you are not careful you can possibly hide both methods and variables of the
superclass.
• A field or variable is said to hide all fields with the same name in superclasses.
Similarly, a static method with the same name in a superclass can hide the method of
the subclass.
Method Hiding
• Method hiding is closely related to method overriding and sometimes programmer
hides the method trying to override it. The concept of overriding allows you to write
code which behaves differently depending upon an object at runtime.
• Static method with the same name in a superclass can hide the method from
subclass because a static method cannot be overridden in Java.
• This example, we assume that p.sleep() will call the sleep() method
from Parent class and c.sleep() will call the sleep() method from child class,
just like it happens in overriding but because sleep() is a static method, instead
of overriding we have hidden the sleep() method.
• The parent class can hold reference to both the parent and child objects.
• If a parent class variable holds reference of the child class, and the value is present in both the
classes, in general, the reference belongs to the parent class variable.
• This is due to the run-time polymorphism characteristic in Java
class Demo_base {
int value = 1000;
Demo_base()
{
System.out.println("This is the base class constructor");
}
}