-4
package test;
public class Test {

     public static void main(String[] args) {
        A a2 = new B();               // 1
        a2.display1(); 
        a2.display();
        ((B) a2).display2();          //  2
        ((A) a2).display();           //  3
        B b1 = new B();
        b1.display1();                //  4
     }
}

class A {
    int a = 10;

    void display() {
        System.out.println("parent class " + a);
    }

    void display1() {
        System.out.println("parent class " + (a + 10));
    }
}

class B extends A {
    int a = 30;

    @Override
    void display() {  
        System.out.println("child class " + a);
    }

    void display2() {
        System.out.println("child class " + (a + 10));
    }
}
  1. whose object is created ?class A or B.
  2. Is this downcasting
  3. why this is not invoking the method of class A? how to invoke method of class A (override one) with this object and not with the object of A.
  4. is this implicit upcasting?
  5. If a class A have a nested Class B than during object creation of class A does object of class b is also formed ?i was not able to use method of class B from object of A
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
ekaf
  • 153
  • 2
  • 13

1 Answers1

1
  1. You do new B(), so obviously a B object is created.

  2. Yes, from the type A to the subtype B which is down the class hierarchy.

  3. Because a2 refers to a B object and which method is called is determined dynamically (at runtime, instead of at compile time) by looking at what the type of the actual object is.

  4. No, there's no casting going on here at all.

  5. I don't understand exactly what you mean here. The type of the variable determines which methods you can call, but which method is actually called depends on the actual type of the object that the variable refers to.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • thanks for the answer .few doubt are 1.if Object of B is created than why i am not able to invoke method of class B .is it because my a2 is refering only to class A. 3. so to call method display() from class A i need to create object of A separately? – ekaf Aug 31 '16 at 11:08
  • 1
    1. Yes, you can only call methods that exist in the type that the variable has (or its superclasses / interfaces) / 3. Yes, or call `super.display();` from a method in class `B`. – Jesper Aug 31 '16 at 11:31