classCastException please help me with real concept

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.

Upvotes: 1

Views: 93

Answers (3)

Anita
Anita

Reputation: 2400

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.

Upvotes: 1

RuntimeException
RuntimeException

Reputation: 1633

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.

Upvotes: 1

Pankaj Shinde
Pankaj Shinde

Reputation: 3689

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?

Upvotes: 1

Related Questions