标签:
* 一、面向对象的特征二:继承性
1 public class TestExtends { 2 public static void main(String[] args) { 3 Student s = new Student(); 4 s.eat(); 5 6 Worker w = new Worker(); 7 w.eat(); 8 9 Person p = new Person(); 10 p.eat(); 11 12 s.setAge(12); 13 s.setName("麻华龙"); 14 System.out.println(s.getName() + ":" + s.getAge()); 15 16 Graduate g = new Graduate(); 17 g.eat(); 18 g.info(); 19 g.show(); 20 } 21 } 22 23 class Person { 24 private String name; 25 private int age; 26 27 public String getName() { 28 return name; 29 } 30 31 public void setName(String name) { 32 this.name = name; 33 } 34 35 public int getAge() { 36 return age; 37 } 38 39 public void setAge(int age) { 40 this.age = age; 41 } 42 43 public void eat() { 44 System.out.println("吃饭"); 45 } 46 47 void walk() { 48 System.out.println("走路"); 49 } 50 private void sleep(){ 51 52 } 53 } 54 55 class A{ 56 57 } 58 59 class Student extends Person{ 60 // class Student extends Person,A{ 61 // private String name; 62 // private int age; 63 private String schoolName; 64 65 public Student(){ 66 67 } 68 public Student(String name,int age){ 69 // this.name = name; 70 // this.age = age; 71 this.setName(name); 72 this.setAge(age); 73 } 74 75 // public String getName() { 76 // return name; 77 // } 78 // public void setName(String name) { 79 // this.name = name; 80 // } 81 // public int getAge() { 82 // return age; 83 // } 84 // public void setAge(int age) { 85 // this.age = age; 86 // } 87 // 88 // 对父类同名的方法的重写、覆盖 89 public void eat(){ 90 System.out.println("应该多吃有营养的"); 91 } 92 public void walk(){ 93 System.out.println("背着书包蹦蹦跳跳的走路"); 94 } 95 public void info(){ 96 eat(); 97 //System.out.println("name:" + name); 98 System.out.println("我是一个学生"); 99 } 100 //不是对父类私有的sleep()方法的重写。 101 private int sleep(){ 102 return 0; 103 } 104 105 } 106 107 108 109 class Worker extends Person{ 110 public void eat(){ 111 System.out.println("工人吃饭"); 112 } 113 114 public void walk(){ 115 116 } 117 } 118 119 class Graduate extends Student{ 120 public void show(){ 121 System.out.println("我是一个研究生"); 122 } 123 }
标签:
原文地址:http://www.cnblogs.com/zhangfan94/p/4263272.html