一、广义的类
①普通类(具体类):
我们平时最常见到的类,有定义、全有实现;
②接口:
存在于概念中的类,
只有定义,没有实现
(Java8 允许在接口中对定义的方法进行实现);
③抽象类:
有定义,至少有一个方法没有实现,且至少有一个方法实现(介于
普通类
和
接口
之间的类)
二、接口
接口
作为一种“画大饼”的类,只有定义(描述了功能),但没有实现。它将方法全部列出,告诉我们它能够干这干那,但一问接口:怎么做到的?它却支支吾吾,大脑空空。
接口的定义与实现的框架如下:
/** Represents an immutable set of elements of type E. */
public interface Set<E>{
public Set();
public boolean contains(E e);
public ArraySet<E> union(Set<E> that);
}
/** Implementation of Set<E>. */
public class ArraySet<E> implements Set<E> {
/** make an empty set */
public ArraySet() { ... }
/** @return a set which is the union of this and that */
public ArraySet<E> union(Set<E> that) { ... }
/** add e to this set */
public void add(E e) { ... }
}
先定义接口,将接口中包含的方法全部列出来;
public interface Set<E>
再实现接口,用一个类来将接口变成现实;
public class ArraySet<E> implements Set<E>
三、几点注意
①接口和抽象类都是不能实例化的,因为其中仍有方法未实现;
②用子类继承并实现接口和抽象类,才可以实例化;
③接口一般都用斜体表示
interface;
四、重载(Overloading)
了解
重写(Overriding)
的人都知道,重载与重写是不同的;
宽泛的来说,子类中与父类
名字相同
但
参数列表不同
的方法称为父类中对应方法的重载。
public class Animals{
void eat();
}
public class Cat{
void eat();
void eat(String food);
}
void eat(String food)便是对父类中eat方法的重载
但如果出现多个重载呢?
public class Animals{
public Animals(){}
void eat();
}
public class Cat{
void eat();
public Cat(){}
void eat(String food){
System.out.println("猫吃"+food);
}
void eat(String food, int remains){
System.out.println("猫吃了"+remains+"只"+food)
}
}
然后我们如下调用:
Cat a = new Cat();
a.eat("老鼠");
a.eat("老鼠",4);
就会发现结果为:
猫吃老鼠
猫吃了4只老鼠
五、重载匹配问题
编译器会根据如下因素自动匹配:
①参数列表
:包括参数数目,参数类型;
②返回值类型
③访问限制
④异常
比如四中第一个a.eat()中只有一个字符串”老鼠”,所以会自动匹配
void eat(String food){
System.out.println("猫吃"+food);
}
而第二个a.eat()中有”老鼠”和4两个参数,就会匹配
void eat(String food, int remains){
System.out.println("猫吃了"+remains+"只"+food);
}