user5106804
user5106804

Reputation:

Java object slicing confusion

I have a base and drive class(inheriting base class). And my based class is having object of drive class. So when I am invoking the overridden function it is giving me right result, by calling the drive class function as the based class is having drive class object. But when i am just printing the variable present in both base and drive class (having same name) from based class object, it prints the value of the variable present in base class. Is there a way i can print drive class variable.

class A
{
    int i = 10;

    public void func(){
        System.out.print("print i :  " +i);
    }
}

class B extends A
{
    int i = 20;
    public void func(){
        System.out.print("print i :  " +i);
    }
}

class MainClass
{
    public static void main(String[] args)
    {
        A a = new B();

        System.out.println(a.i);
        a.func();
    }
}

Output is:-

10
print i :  20

Upvotes: 0

Views: 233

Answers (3)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

 a.i

You are referencing the base class. Base class has "i" and you are referencing it, getting 10.

 a.func()

Second output gives 20 because function gets closest scope i which hides base class i.

Upvotes: 1

Boschi
Boschi

Reputation: 630

You can implement a method ("getter") and override it as well, or then you can access the superclass' variable using the keyword "super":

System.out.println(super.i);

Upvotes: 0

Jeremy
Jeremy

Reputation: 22435

Each class has it's own instance of i. If you wanted B to inherit i from A, you need to remove int i = 20 from B. If you want to initialize i when you construct a new B, do so in a constructor.

public B(int i) {
    this.i = i;
}

However, if you don't want to do that, and want to access i from the parent class, you can refer to it by saying super.i.

class B extends A
{
    int i = 20;
    public void func(){
        System.out.print("print i :  " + super.i);
    }
}

Upvotes: 0

Related Questions