标签:
Java继承与组合
继承
java 中使用extends关键字表示继承关系,当创建一个类时,如果没有明确指出要继承的类,则是隐式地从根类Object进行继承。
public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = new Student(); System.out.println(p.name); } } class Person { public String name; public String sex; public short age; public Person(){ name = "John"; System.out.println("It is a person"); } } class Student extends Person{ public String name; public Student(){ this.name = super.name; //利用super引用父类变量 System.out.println("It is a student"); } } //输出 It is a person It is a student John
public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = new Student(); p.printName(); p.printAge(); } } class Person { private Pet p = new Pet(); /*static{ System.out.println("Person"); }*/ public String name; public String sex; public short age; public Person(String name){ this.name = name; } public void printName(){ System.out.println("My name is" + name); } public static void printAge(){ System.out.println("This is used to print the people‘s age"); } } class Student extends Person{ public String name; public int age; public Student(){ super("John"); this.name = super.name; //利用super引用父类变量 } public static void printAge(){ System.out.println("This is used to print the student‘s age"); } public void printName(){ System.out.println("It is used to print the student‘s name"); } } //输出 It is used to print the student‘s name This is used to print the people‘s age
class Person { public String name; public Person(String name){ this.name = name; } public void printName(){ System.out.println("My name is" + name); } } class Student extends Person{ public Student(){ super("John"); } public void printName(){ System.out.println("It is used to print the student‘s name"); } }
组合
组合是指在设计类的同时,把将要组合的类的对象加入到该类中作为自己的成员变量。
class Student extends Person{ public String name; public School school; //组合 public Student(){ super("John"); this.name = super.name; //利用super引用父类变量 } public void printName(){ System.out.println("It is used to print the student‘s name"); } } class Person { public String name; public Person(String name){ this.name = name; } public void printName(){ System.out.println("My name is" + name); } } class School { public String name; public String address; public void printName(){ System.out.println("School name:" + name); } public void printAddress(){ System.out.println("School address" + address); } }
程序中选择集成或者组合的原则:
标签:
原文地址:http://www.cnblogs.com/zhanglei93/p/5751280.html