---------- android培训、java培训、期待与您交流! ----------
抽象类和接口是java面向对象的两个重要的机制,如果一个类用abstract修饰,则该类称为抽象类,抽象类不能利用new运算符进行创建,所以抽象类一定应该有其子类,而子类通常不是抽象类,也就是说,它必须为父类中的所有抽象方法书写方法体,即重写父类的所有抽象方法。如果子类没有重写父类的所有抽象方法,那么该子类也是一个抽象类,但最终一定会有不是抽象的子类存在。
抽象类与抽象方法有一定的关系。抽象方法是指用abstract修饰,且只有方法声明,没有方法实现的方法。如果一个类包含有抽象方法,则该类一定是抽象类,抽象类中可以不包含抽象方法。此外,抽象类还可以有构造方法。
接口用interface关键字来声明,接口中只能包含常量和抽象方法,且这些成员都是public型的。一个类可以通过implements关键字来使用若干个接口,它弥补java不支持多重继承的不足。如果一个类使用了某个接口,则该类必须实现接口中的所有方法。无法创建接口类的对象,但可以声明接口变量,并把实现该接口的类的对象赋值给它,这称为接口回调,接口回调体现了多态性。接口可以被继承,也可以作为方法的参数和返回值。
抽象类的定义与使用示例:
package com.itheima;
public class Abstract_Test {
public static void main(String[] args) {
Chinese showPerson = new Chinese();
showPerson.speek();
Foreigner elsePerson = new Foreigner();
elsePerson.speek();
}
}
abstract class Person {
public Person() {
System.out.println("人出生:哭.......");
}
public abstract void speek();
}
class Chinese extends Person {
public void speek() {
System.out.println("Chinese:国语");
}
}
class Foreigner extends Person {
public void speek() {
System.out.println("Foreigner:外语");
}
}
接口的使用示例:
package com.itheima;
public class Interface_Test {
public static void main(String[] args) {
Test_1 test_1 = new Test_1();
System.out.println("test_1.method_1(6)=" + test_1.method_1(6));
System.out.println("test_1.method_2(4, 5)=" + test_1.method_2(4, 5));
Test_2 test_2 = new Test_2();
System.out.println("test_2.method_1(6)=" + test_2.method_1(6));
System.out.println("test_2.method_2(4, 5)=" + test_2.method_2(4, 5));
System.out.println("Test_1.A=" + Test_1.A + "\n" + "Test_2.A="
+ Test_2.A);
}
}
interface Computable {
final int A = 300;
int method_1(int x);
int method_2(int x, int y);
}
class Test_1 implements Computable {
public int method_1(int x) {
return x + 6;
}
public int method_2(int x, int y) {
return x * y;
}
}
class Test_2 implements Computable {
public int method_1(int x) {
return x * 6;
}
public int method_2(int x, int y) {
return x * y * 6;
}
}
接口回调示例:
package com.itheima;
public class Interface_Test1 {
public static void main(String[] args) {
Display display;
display = new People();
display.speek();
display = new Monkey();
display.speek();
}
}
interface Display {
public void speek();
}
class People implements Display {
public void speek() {
System.out.println("人说:普通话");
}
}
class Monkey implements Display {
public void speek() {
System.out.println("猴子:胡吼");
}
}