抽象类和接口中的静态方法?
老师,抽象类中的静态方法可以被继承不能被重写,接口中的静态方法不可以被继承,是这样吗?普通方法中的静态方法和抽象方法一样吗?
33
收起
正在回答
2回答
同学你好,1、在接口中添加静态方法带来了一个限制 :这些方法不能由实现它的类继承,也就是说实现类并没有接口中的静态方法,所以声明为接口就访问接口中的内容,这个内容,并不包括接口中的静态方法。
2、其余内容同学的说法是正确的,声明为父类就访问父类,声明为子类就访问子类的,同学可以参考如下例子来理解一下:
1 2 3 4 5 6 7 8 | public interface IFly { static int TEMP= 2 ; void fly(); static void play(){ System.out.println( "飞行的静态方法~" ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 | public class Brid implements IFly{ public static final int TEMP= 3 ; @Override public void fly() { System.out.println( "小鸟会飞~~~" ); } public static void play(){ System.out.println( "小鸟飞的静态方法~" ); } } |
1 2 3 4 5 | public abstract class Animal { public static void eat(){ System.out.println( "生物都会吃饭" ); } } |
1 2 3 4 5 | public class Cat extends Animal{ public static void eat(){ System.out.println( "猫咪吃猫粮~~" ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class TestDemo1 { public static void main(String[] args) { Animal cat2 = new Cat(); cat2.eat(); Cat cat = new Cat(); cat.eat(); IFly brid2 = new Brid(); brid2.fly(); //brid2.play(); System.out.println(brid2.TEMP); Brid brid = new Brid(); brid.play(); System.out.println(brid.TEMP); IFly.play(); } } |
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
java工程师2020版
- 参与学习 人
- 提交作业 9404 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧