Iron
Iron

Reputation: 37

Java converting an object to his superclass and then converting it back to itself keeps the reference

My question is, how is this situation possible?

How is it possible that i can access the value of the text variable from a class of B type?

Is the 'testB' object keeping a reference to the 'testA' object?

CODE:

public class Main {

    public static void main(String[] args) {
        A testA = new A();
        testA.text = "Test";

        B testB = testA;

        System.out.println(((A)testB).text); // This prints "Test"
    }
}

class A extends B {
    public String text = "";

    public String foo() {
        return "foo";
    }
}

class B {

    public String foo2() {
        return "foo 2";
    }
}

Thank you.

Upvotes: 1

Views: 81

Answers (2)

omoshiroiii
omoshiroiii

Reputation: 693

Let's break down this code for you:

public static void main(String[] args) {
    A testA = new A();
    testA.text = "Test";

    B testB = testA;

    System.out.println(((A)testB).text); // This prints "Test"
}

Starting with:

A testA = new A();

You start off by initializing memory of class of 'A' as a new Object of 'A', or in other words, you have created an area within your RAM that is held by an object of class A.

testA.text = "Test";

You then set its property of text to the string literal "Test"

and lastly you initialize memory of class 'B' as a reference to your object 'A'

B testB = testA;

The reason you cannot access the text property without the cast is because testB does not have the property 'text', e.g. the properties and methods you can access are determined by your initialization (B testB gives access to the methods and properties of class B). When acting upon an object with a method however (e.g. myMethod(myClass class)), how that method behaves is determined by what type of object it is. This is a core concept of polymorphism.

Upvotes: 2

Ash
Ash

Reputation: 20

The most common use of polymorphism is the ability of an object to take the form of another object, so it refers to a child class object.

In the code you've posted class A is a subclass of class B. So after the assignment, the object B takes the form of the object A and eventually refers to its memory block. Hence, it returns the value of its text attribute, no matter if you cast it to class A or not.

Upvotes: 0

Related Questions