• Post Reply Bookmark Topic Watch Topic
  • New Topic

Compiler Error while overriding method in Subclass...  RSS feed

 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!