1、抽象类:
1)包含一个抽象方法的类必是抽象类;
2)用abstract关键字声明;
3)抽象类必须被子类继承,子类(如果不是抽象类),必须覆盖抽象类中的全部抽象方法。
2、子类覆写了抽象方法,然后再主方法中通过子类的实例化对象就可以调用子类覆写过的方法。
1 abstract class A{ 2 public static final String FLAG = "CHINA"; 3 private String name = "zhangsna"; 4 public String getName() { 5 return name; 6 } 7 public void setName(String name) { 8 this.name = name; 9 } 10 public abstract void print(); 11 } 12 class B extends A{ 13 public void print() { 14 System.out.println("FLAG=" + FLAG); 15 System.out.println("姓名" + super.getName()); 16 } 17 18 } 19 public class AbstractDemo02 { 20 21 public static void main(String[] args) { 22 B b = new B(); 23 b.print(); 24 } 25 }
输出结果为:
FLAG=CHINA
姓名zhangsna
3、抽象类中的无参构造方法
1 abstract class A{ 2 public A(){ 3 System.out.println("A中的构造方法"); 4 } 5 } 6 class B extends A{ 7 public B(){ 8 System.out.println("B中的构造方法"); 9 } 10 } 11 public class AbstractDemo03 { 12 13 public static void main(String[] args) { 14 B b = new B(); 15 } 16 }
输出结果为:
A中的构造方法
B中的构造方法
4、抽象类中指定参数的构造方法
1 abstract class Person{ 2 private String name; 3 private int age; 4 public Person(String name,int age){ 5 this.setName(name); 6 this.setAge(age); 7 } 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public int getAge() { 15 return age; 16 } 17 public void setAge(int age) { 18 this.age = age; 19 } 20 public abstract String getInfo(); 21 } 22 class Student extends Person{ 23 private String school; 24 public Student(String name,int age,String school){ 25 super(name, age); 26 this.setSchool(school); 27 } 28 public String getSchool() { 29 return school; 30 } 31 32 public void setSchool(String school) { 33 this.school = school; 34 } 35 public String getInfo() { 36 return super.getName() + super.getAge() + this.getSchool(); 37 } 38 39 } 40 41 public class AbstractDemo04 { 42 43 public static void main(String[] args) { 44 Student stu = new Student("zhangsan", 20, "aa"); 45 46 System.out.println(stu.getInfo()); 47 } 48 49 }
输出结果为:zhangsan20aa