Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naive Inheritance Problem - Java

G'day people,

I am feeling embarrass by asking such a naive question. But I can't understand one thing, I have Inheritance structure like this,

enter image description here

B extends A, code I have wrote is as below,

Class A

public class A{
    private int pos = 0;
    public A(){
        this.pos = 12;
    }
    public int getPos(){
        return this.pos;
    }
}

Class B

public class B extends A{
    int spec = 15;
    public B(){
        super();
    }
    public int getSpec(){
        return this.spec;
    }
}

And I have one more class to test, Which will get us to my question.

Class Test

import java.util.*;
public class Test{
    public static void main(String[] args){
        B a = new B();
        ArrayList<A> c = new ArrayList<A>();
        c.add(a);
        System.out.println(c.get(0).getPos());
        System.out.println(c.get(0).getSpec());
    }
}

Question : Now I am creating an instance of B, Which means I can access to my parent class's method getPos() and B's own method getSpec(). But if I create ArrayList with type A(...B is type A too, as it extends A...) and add my B's instance it losses it's ability to access it's own method. What am I doing wrong? Does ArrayList implementation is casting my B to A internally?


Note : My basic understanding of inheritance is parent cannot access child's method except they are protected. But Child can access their parent class's method.

like image 632
TeaCupApp Avatar asked Dec 22 '22 09:12

TeaCupApp


2 Answers

There's no casting involved. What you're doing is no different from this:

A bAsA = new B():

While the object referred by bAsA is truly a B object, it is held by an A variable and thus only A methods are available (unless you explicitly cast it as a B variable).

Since your ArrayList is an ArrayList of A, each item in the ArrayList is treated as an A variable and only A methods are available.

like image 105
Hovercraft Full Of Eels Avatar answered Jan 09 '23 18:01

Hovercraft Full Of Eels


Does ArrayList implementation is casting my B to A internally?

No. There is no "internal casting." You, the programmer, have told the compiler it's a list of A.

You have declared the List as List<A>, which you can read as "a list of A". Since all B are A, you can add any B to a List<A>. On retrieval, however, you're only guaranteed to get back an A, not a B — because it's a List<A>, remember — so the compiler treats everything that comes out of the list as an A, even if (at runtime) it's an instance of B.

like image 40
Matt Ball Avatar answered Jan 09 '23 17:01

Matt Ball