如果两个类具有重合的部分就可以用继承的方式进行处理
下述例子中的Student就继承了Person中的age和name
public class test06{ public static void main(String[] args) { Student S=new Student(); S.age=12; System.out.println(S.age); } } class Person { public String name; public int age; } class Student extends Person { public int score; }
注意:
1.个类有且仅有一个父类
2.子类无法父类的私有属性和私有方法(理论上私有属性是可以在同一函数内的进行访问的)
关于解决子类无法访问父类的问题,可将父类中的关键词private改为protected
public class test{ public static void main(String[] args) { Student student=new Student(); System.out.println(student.hello()); } } class Person { protected String name="lipu"; protected int age; } class Student extends Person { public String hello() { return "Hello, " + name; } }
关于super的使用:在子类的构造函数中调用父类的构造函数就要使用super,否则会报错
class Person { protected String name; protected int age; public Person(String name, int age) { this.name = name; this.age = age; } } class Student extends Person { protected int score; public Student(String name, int age, int score) { super(name, age); this.score = score; } }