/**
* 抽象类
*
* @author LXL 2017年5月8日
*/
// 父类
public abstract class Person {
/**
* 抽象类: 专门用来当做父类, 含有抽象方法, 用abstract关键字来修饰的类
* 含有抽象方法的类必须是抽象类.
* 抽象类不能被实例化. 即不能直接用new关键字去产生对象.
* 抽象类的子类必须覆盖所有的抽象方法后才能被实例化, 否则这个子类还是个抽象类
* 抽象类和普通类一样, 有构造方法,一般方法,属性. 还可以有一些抽象方法
* 抽象类中声明构造方法后, 在子类中必须对其明确调用.
*/
/**
* 抽象方法: 只声明而未实现的方法, 用abstract关键字声明的方法
*/
/**
* 注意 : 构造方法、私有方法、final类型的方法 不能声明为抽象方法
* 因为 : 构造方法只能被声明为 public protect private
* 抽象方法只能被 public protect 修饰
* 静态方法和final方法不能被声明为抽象方法理由同上
*/
String name = "aaa"; // 属性
public abstract String talk(); // 抽象类
}
// 子类
public class Student extends Person {
/**
* 抽象类中声明构造方法后, 在子类中必须对其明确调用.
*/
@Override
public String talk() {
return "姓名:" + this.name;
}
}
// 主函数
public class TestAbstract {
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.talk()); // aaa
}
}
第2种 :
// 父类
public abstract class Person2 {
String name = "bbb"; // 属性
public abstract String talk(); // 抽象类
// 可以声明个构造方法
public Person2(String name) {
this.name = name;
}
}
// 子类
public class Student2 extends Person2 {
public Student2(String name) {
super(name);
}
/**
* 抽象类中声明构造方法后, 在子类中必须对其明确调用.
*/
@Override
public String talk() {
return "2 - 姓名:" + this.name;
}
}
// 主函数
public class TestAbstract2 {
public static void main(String[] args) {
Student2 s = new Student2("test2");
System.out.println(s.talk()); // 2 - 姓名:test2
}
}
第3种 :
public abstract class Person3 {
String name = "ccc";
// 可以有一般方法
public void method(String name){
System.out.println("Person3 - method(String name)");
}
public abstract String talk();
}
public class Student3 extends Person3 {
@Override
public String talk() {
return "Student3 - talk() - 姓名:" + this.name;
}
}
// 主函数
public class TestAbstract3 {
public static void main(String[] args) {
Student3 s = new Student3();
System.out.println(s.talk()); // Student3 - talk() - 姓名:ccc
}
}