淘先锋技术网

首页 1 2 3 4 5 6 7

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