简体   繁体   中英

Can we create an object of a class (super or sub class) which cannot invoke any methods from the class?

This question was asked to one of my friend in an interview.

Assume that there is a class called A which is a super class and a sub class called B . Class A has a method called blah() which is also overridden in the subclass B . So create a object in such a way that object created cannot invoke any of the methods from both class(can use both upcasting and downcasting).Is this possible in java or not. If possible construct the object.

So I tried this but I'm getting only ClassCast Exception at runtime.
So the above mentioned question is possible or not.
Thanks in advance.

This is not possible in java,

static class A{
    public void printF(){

        System.out.println("a");
    }
}
static class B extends A{
    @Override
    public void printF(){

        System.out.println("b");
    }
}
public static void main(String args[]){
    A obj1 = new A();
    obj1.printF();
    B obj2 = new B();
    obj2.printF();

    A obj3 = new B();
    obj3.printF();

    // this will throw error
    B obj4 = (A)new B();
    B obj5 = new A();
}

So we can expect the outputs as below,

  1. obj1.printF() will print a because it is created using the class A
  2. obj2.printF() will print b because it is created using the class B and class A is the superclass of class B because class B is inheriting the class A and class B is overriding the method in class A
  3. obj3.printF() will print b because it is created using class B and due to class B is overriding class A printF() method.And this is using upcasting in java
    (upcasting - Upcasting is the typecasting of a child object to a parent)
  4. B obj4 = (A)new B() or B obj5 = new A(); is not possible in java this is trying to downcast an object implicitly,and this will throw the ClassCastException
    (ClassCastException -Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.)

The approach in java for downcasting is to use instanceOf() method. It is downcasting explicitly.

A obj3 = new B();
if(obj3 instanceof B){
  B obj5 = (B)obj3;
  obj5.printF();
}

(Downcasting-downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM