抽象类:
1、抽象类中可以有非抽象方法。
2、抽象类不能被实例化(不能被创建对象)
3、抽象类是给子类继承用的,子类继承抽象类,就必须实现所有的抽象方法。
抽象方法:
1、抽象方法必须在抽象类里或者接口里
2、没有具体的方法实现,需要子类重写并实现这个方法。
-
- abstract class MyPerson{
- public abstract void eat();
- public void f(){
- System.out.println("Person.f");
- }
- }
-
- class XiaoMing extends MyPerson{
-
- @Override
- public void eat() {
- System.out.println("XiaoMing.eat");
- }
- }
抽象类/方法应用场景:
接口是一种特殊的抽象类
1、接口中所有的方法都是公开抽象的方法。
2、接口中所有的变量都是公开静态常量。
1、接口中所有的方法都是公开抽象的方法。我们可以省略方法前的public abstract 。
- interface MyInterface{
- void eat();
- }
2、接口中所有的变量都是公开静态常量。
- interface MyInterface{
- public static final int x = 2;
- void eat();
- }
我们可以省略变量前的public static final
- interface MyInterface{
- int x = 2;
- void eat();
- }