0

When I create a subclass of parent one , I cannot reach to variables and methods of subclass , note I have declare an object as instant of super class but I define it with subclass like this way :

class A {
    public int x
}

class B extends A {
    public int y;
}

public class C {

    public static main(String arg[]) {
        A obj=new B();
    }
}

in main method I cannot reach to variable y of obj but for x I can , why ? even I have define this obj with B class still I cannot reach to B properties for obj . so I need to declare and define it with B class ! can any one explain ?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
user1841718
  • 187
  • 1
  • 4
  • 15
  • In your main method, A is the variable type and B is the reference type for your obj variable. The compiler allows the variable, obj, to only have access to variable-type fields and methods, since the reference type *can* change, e.g., you can later assign obj to a `new A()` object. – Hovercraft Full Of Eels Dec 22 '18 at 22:13
  • 1
    The in-memory object may be of type `B`, but the *variable* `obj` is of type `A`. And `A` has no property called `y`. Consider an analogy... Let's say you have a reference to a real-world object, a `Car`. You don't know what *kind* of `Car`, all you know is that it's a `Car`. You can't guarantee that you can interact with specific features that only exist on *some* cars, because you don't know what kind of car it is. You can't put the top down, because not every car is a convertible. You can't open the trunk, because not every car has a trunk. Etc. – David Dec 22 '18 at 22:16

0 Answers0