Inheritance and Instance Variables in Java

In this class, We discuss Inheritance and Instance Variables in Java.

The reader should have prior knowledge of inheritance. Click Here.

We take an example and understand the execution of instance variables in inheritance.

Example:

class A

{

int p=40;

void m1()

{

System.out.println(“hello”);

}

}

Class B extends A

{

int q=50;

void m2()

{

int c;

c= p+q;

System.out.println(c);

}

}

The execution of the line c= p+q;

The “p” value is first checked in class B.

If class B does not contain p., check the “p” value in the superclass.

class test

{

public static void main(String args[])

{

B ob = new B();

ob.m2();

}

}

We created an object ob for class B.

The memory is allocated for variables present in both classes A and B.

Modify the above code.

Add a variable int p=50 to class B.

now c = p+ p is written.

The “p” value is taken from class B, which is 50.

How to access the “p” value from class A?

We will discuss the above question in our later class.