class A{
void process() throws Exception{
throw new Exception();
}
}
public class ExtendTest extends A{


void process(){
System.out.print("ExtendTest");
}
public static void main(String[] args) {
A a = new ExtendTest();
a.process(); //line 1
new ExtendTest().process(); // line 2
}
}

Why does this program gives an unhandled Exception at line 1? Line 1 and Line 2 are using same object.

Recommended Answers

All 2 Replies

Line 1 is an A object. a throws the error. When you declare an object like this i dont think the methods are overridden.
try ExtendTest a = new ExtendTest();

You have assigned the variable a as an object of type A. A's process() method throws an exception. You need to wrap the line

a.process();

in a try/catch block. Let me know if this hasn't helped.
Also,

new ExtendTest().process();

doesn't make sense. I think what you want is

ExtendTest et = new ExtendTest();
et.process();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.