Java是一種面向對象的編程語言,在面向對象的編程中,有兩個重要的概念——繼承和組合。
繼承是指一個類可以擴展或繼承一個或多個已有的類,從而擁有已有類的方法和屬性。
// 父類 public class Animal { private int age; private String name; public Animal(int age, String name) { this.age = age; this.name = name; } public void eat() { System.out.println("Animal eat food"); } } // 子類 public class Dog extends Animal { public Dog(int age, String name) { super(age, name); } public void bark() { System.out.println("Dog bark"); } } // 使用繼承 Dog dog = new Dog(2, "Jack"); dog.eat(); // Animal eat food dog.bark(); // Dog bark
組合則是將不同的類組合在一起使用,而不是擴展已有類。組合可以將不同的類的特點進行組合,從而形成一個新的類。
// 車輪類 public class Wheel { private int size; public Wheel(int size) { this.size = size; } public int getSize() { return this.size; } } // 車身類 public class Body { private String color; public Body(String color) { this.color = color; } public String getColor() { return this.color; } } // 汽車類 public class Car { private Wheel wheel; private Body body; public Car(Wheel wheel, Body body) { this.wheel = wheel; this.body = body; } public void getInfo() { System.out.println("This car has a " + wheel.getSize() + " inch wheel, and its color is " + body.getColor()); } } // 使用組合 Wheel wheel = new Wheel(18); Body body = new Body("Red"); Car car = new Car(wheel, body); car.getInfo(); // This car has a 18 inch wheel, and its color is Red