1. Understanding Inheritance in Java
In Java, inheritance serves as a pivotal mechanism enabling one object to inherit all the attributes and behaviors of its parent object. This conceptual framework embodies the Is-A relationship, also known as the parent-child relationship. The 'extends' keyword in Java facilitates the implementation of inheritance, allowing one class to inherit from another.
Example 1: Basic Inheritance Case
In this example, we define two classes: P
and C
. P
serves as the parent class with a method m1()
that prints "This is class P". Class C
is the child class of P
, and it extends P
, inheriting its properties and methods. In addition to the inherited method m1()
, C
introduces its own method m2()
, which prints "This is child of class P". This showcases the fundamental concept of inheritance where a child class can inherit and extend the functionalities of its parent class.
class P {
public void m1() {
System.out.println("This is class P");
}
}
class C extends P {
public void m2() {
System.out.println("This is child of class P");
}
}
Example 2: Parent to Child Inheritance
In this example, we create a class named Test
with a main
method. Inside the main
method, we attempt to create an object of class P
called par
and invoke its methods m1()
and m2()
. However, an error occurs when trying to call m2()
on the parent reference par
because the parent class P
does not have a method named m2()
.
class P{
public void m1(){
System.out.println ("This is class P");
}
}
class C extends P{
public void m2(){
System.out.println("This is child of class P");
}
}
class Test {
public static void main(String[] args) {
P par = new P();
par.m1();
par.m2(); // Error: Cannot call child method on parent reference
}
}
To resolve this issue, we modify the code to use the child class object C
:
class P{
public void m1(){
System.out.println ("This is class P");
}
}
class C extends P{
public void m2(){
System.out.println("This is child of class P");
}
}
class Test {
public static void main(String[] args) {
C chi = new C();
chi.m1();
chi.m2();
}
}
Now, with the object chi
of class C
, both m1()
and m2()
can be called without any errors. This illustrates the importance of using the appropriate class reference when invoking methods to ensure compatibility and access to the correct set of methods based on the class type.
Conclusion:
- On a parent reference, any method in that class can be called:
P par = new P(); par.m1();
- On a parent reference, calling child methods directly is incorrect:
P par = new P(); par.m2(); // Incorrect
- Parent references can hold child class objects:
P par = new C(); par.m1();
- Child references cannot be used to hold parent objects:
C chi = new P();
This discussion sets the stage for further exploration of polymorphism in Java.