Hi All,
We all know about the concepts of Inheritance . For better understanding you can check : Java Inheritance
Now in this post , I will share different cases for inheritance , which would be useful for handling different scenarios in programming.
public class InheritanceDemo1 {
public static void main(String [] args){
Parent parent = new Parent();
parent.m1();
Child child = new Child();
child.m2();
Parent parent1 = new Child();
parent1.m1();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m2(){
System.out.println("This is child class m2 method");
}
}
public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Parent();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m2(){
System.out.println("This is child class m2 method");
}
}
We all know about the concepts of Inheritance . For better understanding you can check : Java Inheritance
Now in this post , I will share different cases for inheritance , which would be useful for handling different scenarios in programming.
Case I :
Take a look on following example and its output:public class InheritanceDemo1 {
public static void main(String [] args){
Parent parent = new Parent();
parent.m1();
Child child = new Child();
child.m2();
Parent parent1 = new Child();
parent1.m1();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m2(){
System.out.println("This is child class m2 method");
}
}
Output will be :
This is parent class m1 method
This is child class m2 method
This is parent class m1 method
Explanation:
parent1 is a reference of Parent type and refers to an object of Child class.Here is no overriding has been done. Just checking which method would be accessed by which reference.If reference of Parent type then parent call method is called.
Case II :
Take a look on following example and its output:public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Parent();
}
}
class Parent {
public void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m2(){
System.out.println("This is child class m2 method");
}
}
Output will be :
error: incompatible types: Parent cannot be converted to Child
Explanation:
child is a reference of Child type and refers to an object of Parent class.Here is no overriding has been done. Just checking which method would be accessed by which reference.In this case we will get compile time error.
That's it , in next post we will check the overriding concept , with inheritance.
No comments:
Post a Comment