World's most popular travel blog for travel bloggers.

Inheritance problem (JAVA)

, , No Comments
Problem Detail: 

enter image description here

Here I have created 2 classes , $A$ is the super class of $B$ , i.e , $B$ inherits the features of class $A$.

Now I don't know exactly what statement (1) does but I am speculating as follows ,kindly correct me if I am wrong ,

An object of $B$ is created whose address has been assigned to the variable $ob$ of class $A$.

Now when statement (2) is called the $add$ function of the class $B$ is executed , but when statement (3) is executed it gives an error saying $e$ doesn't belong to $A$. Why is that ?

With my understanding , I thought statement (1) creates an object of class $B$ via its parent class $A$. Then why its object can't access its data member ? Can anyone explain ?

Asked By : User9523
Answered By : tjhighley

The variable $ob$ is an object reference variable of type $A$. As such, it can only reference those attributes and methods defined in $A$. The attribute $e$ is defined in $B$, not $A$, so $ob$ cannot reference $e$. It is okay to reference $add$ because it is defined in $A$, even though it is overridden in $B$.

Best Answer from StackOverflow

Question Source :

3200 people like this

 Download Related Notes/Documents


Post a Comment

Let us know your responses and feedback