Posts Tagged subclass

Narrowing: Typecasting to Subclass

    Case 1: (ALLOWED):

Super super = new Sub();
Sub sub = (Sub) super;

It is called Narrowing.

Use:
We have an object of subclass which is referenced by Superclass reference. We don’t have any other reference to that object. Now we want to get subclass reference to that object to get access to subclass methods. Then we can perform narrowing. Here object remains the same(of subclass), what narrowing does is gives a reference of subclass to that object.

Case 2: (Gives ClassCastException at run time):


Super super = new Super();
Sub sub = (Sub) super;

Reason:
If object itself is of superclass, we can not have a reference of subclass to it. The superclass object does not have subclass specific members in its scope. So if it is typecasted to subclass, it will still have the superclass members in its scope, so there is no use of narrowing it to subclass. So it is not allowed.
Why the error is at run time, not compile time: At compile time, the compiler does not know what object the super class reference is pointing to. Compiler knows about the reference variable only.
If it points to subclass,

Super super = new Sub();

Narrowing is allowed as in case 1 above.
But if it points to same(super) class, narrowing is not allowed.

Super super = new Super();

So not knowing what the actual case is,compiler does not take any action and leaves it to run time to handle it.

Advertisements

,

Leave a comment

Java Exceptions: Using Exception’s Sub Classes

Syntax of try-catch

try
{
//code which throws some exception
}
catch(XException xe)
{
}
where X is type of exception.

In catch, we have to pass type of exception which is thrown by the code in above try
block.If we know the exact type of excepton thrown, we should use it in catch, as:

catch(SQLException se) {}

But what if we are not sure about type of exception thrown? Here is the solution:

catch(Exception e){}

Exception is superclass of all Exception classes. So a reference of Exception can catch all type of exceptions.
So whatever is the exception type, it will catch it and will not give any error.
To know the type of exception, we can print it:

catch(XException e)
{
System.out.println("Exception type: "+e);
}

Caution: If we are using multiple catch blocks for a single try, always put superclass before subclass, as:

try
{
// code here
}
catch(XException xe){}

catch(Exception e) {}

where XException may be any exception as SQLException,ClassNotFoundException etc.

Putting Exception before XException will produce error.

try
{
// code here
}

// this will give compilation error
catch(Exception e) { }

catch(XException xe) { }

,

Leave a comment