0

NOTE : This question was asked to me in an Interview

We have 3 classes having different properties.

class A{}

class B extends A{}

class C extends A{}

Can I call any method present among these 3 classes with a Single Obj ?

I got confused because class B don't have properties of class C and viceversa.

Is there any way to make this possible ?

Rajat Sangrame
  • 311
  • 3
  • 18
  • so you did answer no you can't, right? – Eugene May 22 '18 at 12:13
  • The question isn't clear. Obviously not with the exact declarations given. – Dave Newton May 22 '18 at 12:13
  • I said sorry I don't know. – Rajat Sangrame May 22 '18 at 12:14
  • :) that is a terrible start in an interview - you just stated the reason in your last statement – Eugene May 22 '18 at 12:14
  • @Rajat Sangrame, I think you are asked about "Diamond Problem" in an interview and you can search more about it on internet. – Jay Dangar May 22 '18 at 12:15
  • He also told me that this concept is used in Android. – Rajat Sangrame May 22 '18 at 12:16
  • @RajatSangrame *What* "concept"? From `C` you cannot call `B` instance methods with the declarations as shown--there is no relationship between `B` and `C` other than they share the same parent class. – Dave Newton May 22 '18 at 12:24
  • @DaveNewton Exactly.. Thats what I though. But he showed me some example calling a AdaperClass from MainActivity and was talking some shit about Modals. I didn't get it. – Rajat Sangrame May 22 '18 at 12:29
  • @RajatSangrame And you were correct--with the declarations shown it isn't possible. If you create a *new* class that composites a `B` and `C` *then* you can. Not until then. (There are a few other mechanisms as well, even without getting into byte-code manipulation, which is another option.) – Dave Newton May 22 '18 at 12:45

2 Answers2

0

Can I call any method present among these 3 classes with a Single Obj ?

You could not call any method. Only method declared in A class with any object with A type of reference

Uladzislau Kaminski
  • 2,113
  • 2
  • 14
  • 33
  • I don't think you got the point, you can call a method from `A` with a reference of type `B` as long as that method is inherited. – Eugene May 22 '18 at 12:21
  • Is there any way to do this possible ? May be I am missing any declaration. He also told me this concept is used in Anroid – Rajat Sangrame May 22 '18 at 12:25
0

I think the question that you were asked was about Diamond Problem, you can check more about it here. --> https://www.geeksforgeeks.org/multiple-inheritance-in-c/

Coming to your Question, as Java does not support multiple inheritance, you can't call any method present among these 3 classes with a Single Object. For solving this "Diamond Problem", Java has something called Interfaces. So, Android supports java and "Interfaces" is the concept that the interviewer was talking about to solve "Diamond Problem" in Android and Java.

Jay Dangar
  • 3,271
  • 1
  • 16
  • 35