Java抽象类与接口比较

xiaoxiao2021-02-28  131

1、抽象类

/** * 抽象类用于总结一系列相似对象的共有特征 * * 抽象类可以有普通成员变量、非抽象方法 * 抽象类可以没有抽象方法 * 抽象类中抽象方法必须显式声明为public abstract * 抽象类中的成员应该有相关性 * * 继承类必须实现抽象方法 * @author Administrator * */ public abstract class Animal { private int i; private static double j; /*private abstract void yell();*/ // The abstract method yell in type Animal can only set a visibility modifier, one of public or protected public abstract void yell(); // 抽象方法必须显式声明public abstract,并且在子类中必须实现 public void weight() {} // 可以有非抽象方法 private void weight2(){} // 可以有私有非抽象方法 }

2、接口

/** * 抽象类用于定义一系列操作的集合,这个集合中成员可以没有任何相关性,但大部分都是有相关性 * * 成员变量必须是public static final * 成员方法必须是public abstract * 抽象方法不能有实现 * * 实现类必须实现接口中所有方法 * @author Administrator * */ public interface IAnimal { /*private int i = 0;*/ // 编译出错: Illegal modifier for the interface field IAnimal.i; only public, static & final are permitted public static final double j = 0.0; // 标准写法 String catetory = null; // 简写 /*private void yell();*/ // 编译出错: Illegal modifier for the interface method yell; only public & abstract are permitted public abstract void yell(); // 标准写法 public void yell2(); // 简写 }
转载请注明原文地址: https://www.6miu.com/read-36860.html

最新回复(0)