Java核心技术_笔记6-1

1.接口不是类,而是对类的一组需求描述
任何实现接口的类都要包含并实现接口中的方法

2.
public interface Comparable
{
int compareTo(Object other);
}

3.
public interface Comparable< T>
{
int compareTo(T other);
}
声明泛类型后必须用T声明对象

4.
接口中的所有方法自动地属于public。
在接口中声明方法时,不必提供关键字public
在类中实现的时候还是要加public

5.
接口不能提供实例域
不应该实现方法
可以看成没有实例域的抽象类

6.
声明类实现接口用implements
(1)
class Employee implements Comparable
具体方法实现
public int compareTo (Object otherObject)
{
Employee other=(Employee) otherObject;
return Double.compare(salary,other.salary );
}
(2)提供类型参数的实现
class Employee implements Comparable< Employee>
具体方法实现
public int compareTo (Employee otherObject)
{
return Double.compare(salary,other.salary );
}

7.
Manager是Employee的子类,但类型转换比较不允许
public int compareTo (Employee otherObject)
{
Manager other=(Manager) otherObject;
}

8.
接口不能构造对象,不能new实例化
x=new Comparable()是错误
但可以声明
Comparable x
必须引用实现了接口的类对象
x=new Employee();

9.
验证x是否实现Comparable接口
x instanceof Comparable

10.接口可以继承其他接口
可以包含静态常量
默认自动设为public static final

public interface Powered extends Moveable
{
double milesPerCallon();
double SPEED.LIHIT = 95;
}

调用常量Powered.SPEED.LIHIT

11.类可以使用多个接口
class Employee implements Cloneable , Comparable

12.抽象类和接口很相似,使用接口的目的是可以使用多个,而抽象类一次只能一个

13.定义的接口中不应该实现方法
但可以设置默认的方法
public interface Comparable
{
int compareTo(Object other);
}
变为
public interface Comparable
{
default int compareTo(Object other){
return 1};
}
加上default可以默认返回1

14.接口默认冲突
(1)超类优先.如果超类提供了一个具体方法 , 同名而且有相同参数类型 的默认方法会被忽略
(2)一个类包含两个 都有同名同参数的默认方法的接口
用 接口名+super+方法名 选择一个
class Student implements Person,Named
{
public String getName (){return Person.super.getName(); }
}

15.从超类和接口继承了相同的方法
例如假设Person 是一个类,Named有与Person同名方法

Student 定义为 :
class Student extends Person implements Named { … }
在这种情况下, 只会考虑超类方法 , 接口的所有默认方法都会被忽略

猜你喜欢

转载自blog.csdn.net/Matrix576/article/details/82455450