0

I have a base class and a derived class. The code I am writing is

class Base {
    ...
}

class derived extends base {
}

class Main {
    public static void main(String[] args){
        derived d = (derived) new Base(); //throws a ClassCastException 
    }
}

How is this handled? I would like to call the base class methods without the use of super keyword.

2
  • Base is not a Derived so it cannot be cast to Derived Commented Mar 7, 2013 at 11:22
  • ... while Derived is a Base so it can be casted to Base ;) Commented Mar 7, 2013 at 11:25

4 Answers 4

1

Base class is a super class and derived class is subclass. You can not catch object of super class in reference of subclass.

Base b = new Derived();

Above instruction will work but

But following will not work.

Derived d = new Base();
Sign up to request clarification or add additional context in comments.

Comments

0

You can just call the methods of the superclass without the use of super.

Base:

public class Base {

    public void print() {
        System.out.println("Base");
    }

}

Derived:

public class Derived extends Base {...}

Main:

public static void main(String[] args) {
    Derived d = new Derived();
    d.print();
}

Prints out:

Base

Comments

0

actually 'Base' is not 'Derived', so casting is not possible.

it would have been possible in following case

Base b = new Derived() Derived d = (Derived)b;

Comments

0

Downcasting is not possible in java. It is only possible when base class stores the reference of derived class

Base b = new Derived()

// Check is required. It may lead to ClassCastException otherwise
if (b instancof D)     
    Derived d = (Derived) b;  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.