//继承 //扩展父类的功能 //在java中使用extend关键字实现继承 //在java中只允许单继承 //子类不能直接访问父类的私有成员 /* * */ //父类 公有的 class Person{ private int age ; private String name ; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void tell(){ System.out.println("姓名:"+getName()+" 年龄:"+getAge()); } } //继承父类 class Student extends Person{ // private int age ; // private String name ; private int score ; // public int getAge() { // return age; // } // public void setAge(int age) { // this.age = age; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public void say(){ System.out.println("成绩"+getScore()); } } //Java中可以实现多层继承,只要是单继承模式就可以了 class Work extends Person{ int age ; private String Sex ; public String getSex() { return Sex ; } public void setSex(String sex) { Sex = sex; } } class Worker extends Work{ public void tell(){ System.out.println(age); //可以直接访问父类中的非静态成员 } } class HelloWorld{ public static void main(String[] args){ //只用实例化子类就行了 Student s = new Student(); //通过子类去访问父类中的方法 s.setAge(24); s.setName("YANGYUANXIN"); s.setScore(100); s.tell(); s.say(); Work wo = new Work(); wo.setSex("男"); String sex = wo.getSex(); System.out.println("性别:"+sex); } }