1

when an object of subclass is assigned to the variable of a super class,why only those members are accessible which are defined by the superclass

class A { 
    int i=10;
    void adsip() {
        System.out.println(i);
    }
}

class B extends A {
    int j=20;
    void bdsip() { 
        System.out.println(i+j);
    } 
}

class inherit4 { 
    public static void main(String[] x) { 
        A a=new A();
        B b=new B();
        System.out.println("b.i="+b.i+"b.j="+b.j);
        b.adsip();
        b.bdsip();
        a=b;
        System.out.println("a.i="+a.i);
        a.adsip();
    }
}

ABOVE CODE IS WORKING FINE but after adding a.j and a.bdisp(); error is generated,as far as i know a & b in the above code represent refrence to memory allocation of objects of class A & B then why code is not able to access a.j and a.bdsip(); in above code.

Vartlok
  • 2,539
  • 3
  • 32
  • 46

3 Answers3

1

ClassCastException - Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x);

Also please refer this thread. Can someone explain “ClassCastException” in Java?

Community
  • 1
  • 1
Pankaj Shinde
  • 3,361
  • 2
  • 35
  • 44
1

why only those members are accessible which are defined by the superclass

Because, at runtime, the superclass reference may be pointing to a superclass instance or instance of any class in the subclass hierarchy.

superclass has method m1, but subclass has method m1 and m2. You want to access m2 using a reference of superclass. But what if, at runtime, the reference is pointing to an instance of superclass (which does not have m2) ?

So the end result is that - At runtime, the only members that are guaranteed to be accessible using superclass reference are the ones defined in the superclass.

RuntimeException
  • 1,593
  • 2
  • 22
  • 31
1

In inheritance child can access parent data but the reverse is not possible. parent can't access child data. So here object of class A , a can't access Class B's method or data.

Anita
  • 2,352
  • 2
  • 19
  • 30
  • 1
    You say -parent can access child data but the reverse is not possible. But A is the parent. It cannot access class B's method. Please clarify. – RuntimeException Mar 06 '14 at 07:10
  • 2
    *In inheritance parent can access child data but the reverse is not possible* you're wrong. Children classes can access to `protected` and `public` data in parent class (it can also access to `default` data if the child class is in the same package as the parent class), but parent class has no idea of the specific data in the children classes... – Luiggi Mendoza Mar 06 '14 at 07:10