+ 1
Can parent class inherit the properties of child class in inheritance? If yes/no , in what conditions
Interview questions
7 Respostas
+ 2
Mirielle👽 can you give some examples for this case?
+ 2
The child inherits from its parent it works only one way.
if you create method in child that does not exist in parent and try and call it using a parent refrenece variable pointing to a child object then that method will not exist.
+ 1
I doubt if that can be done.
The concept of inheritance will collapse if the parent inherits from the child. I'm not really sure on this one and would like to hear what others have to say.
+ 1
The reference variable of the Parent class is capable of holding its object reference as well as its child object reference.
It is not possible if the reference variable of child class is trying to hold it's parent object reference.
https://code.sololearn.com/cxYP3U57YeS8/?ref=app
+ 1
I think No. Inheritance concept is to inherit properties from one class to another but not vice versa.
But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....
Edit:
https://code.sololearn.com/cgSpnEL77hXf/?ref=app.
+ 1
public class Program {
public static void main(String[] args) {
A ab = new B();
ab.method1(); // B.method1() override
((A) ab).method1(); // B.method1() override
((B) ab).method1(); // B.method1() override
((B) ab).method2(); // B.method2()
}
}
class A{
void method1() {System.out.println("A.method1()"); }
}
class B extends A{
void method1() {System.out.println("B.method1() override"); }
void method2() {System.out.println("B.method2()"); }
}
0
class Animal{
void eat(){
System.out.println("This animal can eat");
}
}
class Bird extends Animal{
void fly(){
System.out.println("This animal can fly");
}
}
class Program{
public static void main(String args[]){
Animal a=new Bird();
((Bird)a).fly();
}
}