先贴代码后分析:
class Person {private int age;public void setAge(int age) {if (age < 0 || age > 200)age = 0;else {this.age = age;}}public int getAge() {return age;} public void printInfo() {System.out.println("age = "+age);}public Person () {System.out.println("Person ()");}public Person (int age) {System.out.println("Person (int age)");this.age = age;}}class Student extends Person{private String school;public void setSchool(String school) {this.school = school;}public String getSchool() {return school;} public Student(String school) {/* will call the super() *///super();super(5);System.out.println("Student(String school)");this.school = school;}/* override */public void printInfo() {System.out.println("school = "+school+"; age = "+getAge());}}public class Ext4 {public static void main (String args[]) {Student stu = new Student("ustc");//stu.setAge(10);System.out.println(stu.getAge());System.out.println(stu.getSchool());stu.printInfo();}
}
这段代码里面有技术含量的也就是:实现子类构造函数之前首先会调用父类的构造函数,但是如果父类构造函数有好几个,那实现哪一个构造函数呢?我们可以使用super()来代替父类。其中super要放到子类构造函数的首行。
abstract class Father {private int money; public int getMoney() {return money; }public void setMoney(int money) {this.money = money; }public abstract void study();
}interface A {public static final int i = 10;public abstract int getNum();
}interface B {public static String name = "InterfaceB";public abstract String getName();
}class Son extends Father implements A,B{public int getNum() {return i;}public String getName() {return name;}public void study() {System.out.println("I am study"); }}public class Ext7 {public static void main (String args[]) {Son son = new Son();System.out.println(son.getName());son.study();}
}1. 抽象类抽象类的不能直接定义对象,必须间接通过子类继承抽象类之后再去定义对象,而且,抽象类的子类必须要首先实现抽象类的中的抽象方法。继承类时候,子类只能有一个父类。但是可以有多个接口。
2.interface中的成分即使你不去将成员定义为全局常量(如果你定义为私有或者protected会报错),以及虚函数,默认也是这个效果。在子类中,一定要实现接口中的虚函数。
3.父类中的私有成员,子类不能直接调用。父类中的public fuction1你不可以在子类中改成private fuction1。在父类中的private fuction1在子类中可以声明public fuction1方法的实现。
4.final类不再有子类,final方法不能被覆写,final变量成为常量,值不能被修改。