java的抽象方法为什么不能是static、final、private?

1、java的抽象方法为什么不能用static修饰?类抽象方法?

 

  如上代码,在抽象类中定义static属性是没有问题的,但是定义抽象方法时是不能定义为静态(static)的,否则编译器会报错:The abstract method geta in type abstractTest can only set a visibility modifier, one of public or protected

  我们只定义静态static方法完全OK,因为静态方法是属于类的,所以静态方法必须满足给类调用,如果通过类无法调用,那么这种静态方法肯定是不对的。为了达到这一要求,static方法就必须有方法体,即已经实现了,也就不是抽象方法了。所以静态(static)方法不能是抽象方法,即abstract不能与static同时修饰方法。即没有类抽象方法。

  如果abstract和static一起修饰已经实现的方法呢?

 

  编译时会报错:Abstract methods do not specify a body

  即只要有abstract修饰方法,则必须定义为抽象方法的格式,否则编译报错。其次,在main方法中调用静态方法编译器没有报错,但是运行时会报错:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

The abstract method out in type abstractTest can only set a visibility modifier, one of public or protected

Abstract methods do not specify a body

 

at firstChap.abstractTest.out(abstractTest.java:6)

at firstChap.abstractTest.main(abstractTest.java:10)

2、abstract不能和final一起出现

  abstract修饰的类需要被子类继承,abstract修饰的方法需要子类重写,但是final修饰的类不能被继承,final修饰的方法也不能被子类重写。

3、abstract不能和private同时出现

  因为abstract修饰的方法必须通过子类重写才有效,而private修饰的方法对子类不可见,即父类中如果存在private abstract void out();而子类中有private void out(){},则它们是两个不同的方法,子类中的out方法不是对父类的重写,而是属于子类独有的方法。

 

 报错:The abstract method out in type abstractTest can only set a visibility modifier, one of public or protected

 

 

猜你喜欢

转载自www.cnblogs.com/datamining-bio/p/10007567.html