Pallavi Prasad
Pallavi Prasad

Reputation: 1

How to handle ClassCastException in java

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.

Upvotes: 0

Views: 4522

Answers (4)

Mohan Raj B
Mohan Raj B

Reputation: 1026

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;  

Upvotes: 0

Ankit
Ankit

Reputation: 6622

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;

Upvotes: 0

mklnwt
mklnwt

Reputation: 61

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

Upvotes: 0

Jeevan Patil
Jeevan Patil

Reputation: 6089

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();

Upvotes: 1

Related Questions