aspose file tools
The moose likes Beginning Java and the fly likes Compiler Error while overriding method in Subclass... Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Compiler Error while overriding method in Subclass..." Watch "Compiler Error while overriding method in Subclass..." New topic
Author

Compiler Error while overriding method in Subclass...

Mihir Patel
Greenhorn

Joined: Apr 26, 2011
Posts: 18

When we override the method in the Subclass and provide it a more restrictive access modifier then why it give a compile time error and not a run time error?

for example: In below example why it gives comiple time error and not run time error.

Class A{
public void testMethod(){}
}

Class B extends A{
private void testMethod(){}
}

A objA = new A();
objA.testMethod();
John Jai
Bartender

Joined: May 31, 2011
Posts: 1778
The compiler senses that at run time a B's instance can be assigned to an A's reference. Why do you think it should give a run time error?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 3867
    
    1

Compile-time errors are much easier to find and fix than run-time errors. So if the compiler can see that something is an error then it will say so. And overriding with greater restrictions is an error.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Compiler Error while overriding method in Subclass...
 
Similar Threads
Variables and Methods?
Protected Method
Regarding method calling
does static methods inherit ? what about private ?
over ridden method and super constructor