Java类之间的关系
在JAVA中,类是程序的基本组成单位,几乎所有代码都会写在类当中,所以类与类之间的关系也是程序运行的关键。
一、关联
关联表现为一个类作为另一个类的属性存在于其中
public class A{
private B b;
}
public class B{
}
二、依赖
一般来说,一个类作为另一个类当中某方法的参数存在就是依赖
public class A{
public void way(B b){
}
}
public class B{
}
三、聚合与组合
聚合关系
把这两个放在一起是因为分布太清他们之间的差别,首先他们都是一种特殊的关联关系都是整体与部分的关系。
public class SmartCar {
/**
* 引擎,动力
*/
private Engine engine = new Engine();
public void drive(Instruction instruction) {
switch (instruction.getContent()) {
case "speed-up":
engine.setSpeed(instruction.getParam());
break;
case "slow-down":
engine.setSpeed(instruction.getParam());
break;
default:
// do nothing
}
System.out.println("智能汽车正在以" + engine.getSpeed() + "码的速度行驶");
}
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
}
public class Engine {
/**
* 气缸
*/
private Cylinder[] cylinder = new Cylinder[8];
/**
* 转速
*/
private int speed;
/**
* @return the cylinder
*/
public Cylinder[] getCylinder() {
return cylinder;
}
/**
* @param cylinder
* the cylinder to set
*/
public void setCylinder(Cylinder[] cylinder) {
this.cylinder = cylinder;
}
/**
* @return the speed
*/
public int getSpeed() {
return speed;
}
/**
* @param speed
* the speed to set
*/
public void setSpeed(int speed) {
this.speed = speed;
}
}
四、继承
继承能使子类拥有父类中除某些特定之外方法与属性,使代码能够横向扩展,再配合抽象、方法覆盖的使用也能规范子类的建立,增强代码复用。
public class Animal {
public void eat() {
System.out.println("这是一只动物");
}
}
public class Cat extends Animal {
public void eat() {
System.out.println("这是一只猫");
}
}
public class Dog extends Animal {
public void eat() {
System.out.println("这是一只狗");
}
}
public class App {
public static void main(String[] args) {
// Animal a4 = new Cat();
// Cat c3 = (Cat) a4;
// Dog d2 = (Dog) a4;
// a4.eat();
Cat c2 = new Cat();
Animal a2 = c2;
a2.eat();
Animal a5 = new Animal();
Cat c4 = new Cat();
Animal a = new Animal();
Cat c = new Cat();
Dog d = new Dog();
Animal a1 = new Cat();
if (a1 instanceof Animal) {
System.out.println("a1 是动物");
} else {
System.out.println("a1 不是动物");
}
if (a1 instanceof Cat) {
System.out.println("a1 是猫");
} else {
System.out.println("a1 不是猫");
}
if (c instanceof Animal) {
System.out.println("c 是动物");
} else {
System.out.println("c 不是动物");
}
if (d instanceof Animal) {
System.out.println("d 是动物");
} else {
System.out.println("d 不是动物");
}
if (c instanceof Cat) {
System.out.println("c 是猫");
} else {
System.out.println("c 不是猫");
}