Can parent class inherit the properties of child class in inheritance? If yes/no , in what conditions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can parent class inherit the properties of child class in inheritance? If yes/no , in what conditions

Interview questions

17th Feb 2020, 7:20 AM
palak pandey
palak pandey - avatar
7 Answers
+ 2
Mirielle👽 can you give some examples for this case?
17th Feb 2020, 9:42 AM
palak pandey
palak pandey - avatar
+ 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.
18th Feb 2020, 1:29 AM
D_Stark
D_Stark - avatar
+ 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.
17th Feb 2020, 8:00 AM
Avinesh
Avinesh - avatar
+ 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
17th Feb 2020, 10:23 AM
Avinesh
Avinesh - avatar
+ 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.
17th Feb 2020, 10:53 AM
Jayakrishna 🇮🇳
+ 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()"); } }
17th Feb 2020, 11:27 AM
zemiak
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(); } }
9th Aug 2022, 4:44 PM
Abhay Bhaskar
Abhay Bhaskar - avatar