This Java slides gives comprehensive understating of :
a) Inheritance
b) super keyword and constructors
c) hierarchical super constructor and execution of blocks and initilaizers
d) static methods and their speciality
e) Method overriding versus overloading
f) why static methods cannot be overridden
h) private methods : why they are not overridden
g) rules of overriding :Exceptions to be thrown
h) dynamic method dispatch what and why
Project Based Learning (A.I).pptx detail explanation
Java Inheritance Types and Concepts
1. Inheritance: A brief recap
• Inheritance is of 4 types: Single, Multilevel, Multiple
and Hybrid( also known as hierarchical).
• Java does not support Multiple inheritance with
sohamsengupta@yahoo.com 1
classes.
• In java, if a class A inherits from another class B, the
syntax is going to be :
class A extends B
{
// codes ( data & method & blocks if any)
}
2. More on Inheritance
• Here class A is called the child/ derived class
• Class B is called the base/parent class
• With respect to the child class, the base class is
referred to as “super”.
• All non-private data and method are inherited
from the base class to the derived or child class.
• Inheritance bears the polymorphism concept
that incorporates the code reusability and
method overriding paradigms.
sohamsengupta@yahoo.com 2
3. Sample Code Snippet
class Base
{
int x=940;
static int percentage=94;
void show(){
System.out.println(“Your score is ”+x);
}
}
class Child extends Base
{
int y=89;
void display(){
System.out.println("My parent's score was "+x); // x is now available here
System.out.println("My parent's score was "+super.x); // x is accessible by super
System.out.println("My parent's score was "+this.x); // x is now available here
System.out.println(“Parent’s percentage can be expressed as ”+percentage+ “,”+Base.percentage+
“,”+Child.percentage+ “,”+super.percentage);
System.out.println(“I’m child with marks “+y);
}
}
class A
{
public static void main(String[] args){
Child ch=new Child();
ch.show(); // show in Base available to Child
ch.display();
}
}
sohamsengupta@yahoo.com 3
4. When a child-class field has name as that of one in the base class
class Base
{
int x=940;
}
class Child extends Base
{
int x=719;
void show(){
System.out.println("My marks is "+x);
System.out.println("Parent's marks was "+super.x);
}
}// super.x denotes Base-class data. Methods in child class with same name
//can be accessed likewise
class A
{
public static void main(String[] args){
Child ch=new Child();
ch.show();
}
} // keyword “super” cannot be accessed from within static context.
sohamsengupta@yahoo.com 4
5. Role of Constructors in Inheritance
class Base
{
Base(){
System.out.println("From Base Constructor");
}
}
class Child extends Base
{
Child(){
System.out.println("From Child Constructor");
}
}
class A
{
public static void main(String[] args){
Child ch=new Child();
}
}
When the child class constructor is invoked, the following
steps take place behind the scene…
1. The static blocks and initializers in the Base class
execute when the class is loaded into memory
followed by the same in the Child class
2. Now for each object of Child class, first the non-static
blocks and constructor of base class execute
3. Then those in the child class execute.
FAQ:
1. We are not calling the base-class constructor, then how
come the base-class constructor is invoked?
Answer: See, although the call isn’t explicit, there is an
implicit call to super(), the default/no-arg Base class
Constructor at the very first line in Child().
However, if there is not any no-arg constructor in the base
class it’ll be an error (Onto next slide)
sohamsengupta@yahoo.com 5
6. super() constructor
class Base
{
Base(int x){
System.out.println("From Base Constructor "+x);
}
}
class Child extends Base
{
Child(){ // Error super() not found; call super(940);
System.out.println("From Child Constructor");
}
}
class A // call to super constructor must be the very 1st line in child constructor
else won’t compile
{
public static void main(String[] args){
Child ch=new Child();
}
}
sohamsengupta@yahoo.com 6
7. Method overriding
1. If a child class redefines an inherited method
present in the Base class, it’s known as a case of
overriding and the method in the base class is
said to have been overridden in subclass.
2. private methods can never be overridden since
they are not inherited.
3. static methods can never be inherited.
4. overriding cannot impose more restrictive access
on the method
5. Its parameter list is kept unchanged.
6. Return type generally same.( details later)
7. Can never declare to throw broader checked
Exceptions. (More on this later)
8. Method overriding is Runtime Polymorphism.
sohamsengupta@yahoo.com 7
8. An example of method overriding
sohamsengupta@yahoo.com 8
class Base
{
void show(){
System.out.println("Hello");
}
}
class Child extends Base
{
void show(){
System.out.println("Born!");
}
}
class A
{
public static void main(String[] args){
Base ref=new Base();
ref.show(); // output: Hello
ref=new Child(); // the ref to Base can hold obj of
// Child
//But converse isn't true without explicit type cast.
// type cast may turn out to be fatal
//ClassCastException depending on code
ref.show(); // output: Born! it's because, the
// ref although being a reference of Base, holds
//object of Child
// this is runtime( ? ) polymorphism or dynamic
method dispatch
}
}
9. static methods can’t be overridden
sohamsengupta@yahoo.com 9
class Base
{
static void show(){
System.out.println("Hello");
}
}
class Child extends Base
{
void show(){
System.out.println("Born!");
}
}
// Error… to avoid: either both should be
static or neither should. Well, let’s make
both static. Now it compiles. But
overriding is not possible. Create an
object of Child and store to a Base’s
reference. Call the method show(). But
Dynamic method dispatch is never seen.
class A
{
public static void main(String[] rt){
Base ref=new Child();
ref.show();
}
}
Output: Hello.
So, static methods are not overridden as
they don’t follow the rule of dynamic
method dispatch
10. Why overriding can’t impose more restrictive access?
Assume, if it were possible, the method show()
in default access-specifier in class Base is
overridden in class Child to be private. OK up to
this!
Now just think of dynamic method dispatch
where the decision to call which version of the
method is taken at runtime. So, the code will
compile. But, poor Programmer! He/she hardly
knew that this won’t work since the method is
imposed private access in Child class. This will
make to code inconsistent in every aspect.
sohamsengupta@yahoo.com 10
11. Why no multiple Inheritance in Java ?
Assume a class A has 2 subclasses B and C
and that each overrides a method, say,
method1() and also assume that if multiple
inheritance were possible, a class D extending
both B and C. So, question will arise which of
the implementations of the same method will the
class D inherit? This is a fallacy. This is known
as the “Deadly Diamond of Death” problem
sohamsengupta@yahoo.com 11
12. More on Inheritance
if you add the keyword “final” before a method
it can’t be anymore overridden.
If it’s used with a class, the class can’t be
anymore inherited or sub-classed.
In order of decreasing restriction, the access
specifiers are private, default, protected and
public
So far we’ve covered only access specifiers with
methods and data but not with class itself. We’ll
see it shortly.
sohamsengupta@yahoo.com 12
13. Abstract Methods & Classes
An abstract method is one, which does not declare any
body. Eg. abstract void show();
An abstract class is one which has the keyword abstract
associated with its declaration. We can’t create objects
of abstract classes due to compilation errors.
Abstract classes may have constructors.
If a class contains at least one abstract method, it must
be declared abstract. But an abstract class may have no
abstract methods at all.
Any class that inherits an abstract class, will either
define all the inherited abstract methods, if any, or be
itself declared abstract.
The keyword “final” does not apply with the keyword
“abstract”. Also an abstract method can’t be private.
The reference to Base can hold object of Child. But here
basrRef can’t access methods which are not in Base.
sohamsengupta@yahoo.com 13
14. iinnssttaanncceeooff ooppeerraattoorr
It’s a binary operator taking first operand as a
reference of a class and the second as a class name
itself.
If the object contained by the reference is of the second
operand class type or a sub type, it returns true else
false.
If the reference and class name are not bound by single
or multilevel inheritance hierarchy, compilation error
occurs complaining of inconvertible or incompatible
types.
Java.lang.Object is the Universal superclass. Every
class inherits from Object clas
An Example of instanceof operator
sohamsengupta@yahoo.com 14
16. Overloading Versus Overriding
• Exhibited inside a class
• Return type can be different
and does not play any role
• Compile time polymorphism.
• Parameters must be different
in regard of type, number,
and/or order.
• No restriction imposed on
declaring Exceptions
• Reference Arguments are
passed depending on the type
of reference not the object it
refers to.
• Can’t be generally prevented.
• Requires both Base & Child
class
• The overridden method must
have return type either same
or super type of the overrider
method.
• Runtime plymorphism
• Parameters must be same.
• Cannot declare to throw
broader checked
exceptions( details later)
• Dynamic method dispatch is
dependent on the type of the
object not the reference type.
• We can prevent overriding by
declaring the method to be
final.
sohamsengupta@yahoo.com 16