关联
它表示类与类之间的连接,它使得一个类知道另一个类的属性和方法;关联是类与类,类与接口之间的一种比较强烈的关系,具有长期性。
代码体现:
1.B作为A的属性出现在了A中
2.关联类A引用了被关联类B的全局变量
依赖
它表示类与类之间的连接,表示一个类依赖于另外一个类的定义,方向是单向的;它具有偶然性,临时性,关系较弱。
例如:
public class Person {
private String name;
private int code;
private int age;
//构造函数 初始化类里的属性
/*
* 函数的重载 类名相同 参数不同
*/
public Person(String name,int code,int age){
this.name = name;
this.age = age;
this.code = code;
}
public Person() {
this.name = "杖伞";
this.age = 120;
this.code = 14343654;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//关联
private Cock c ;
public void setC(Cock c) {
this.c = c;
}
public void eat() {
System.out.println(this.name + "吃" + c.getName());
}
public void bamao() {
System.out.println("给" + c.getName() + "拔毛");
}
public void qieduqn() {
System.out.println("给" + c.getName() + "切段");
}
public void xiaguo() {
System.out.println("给" + c.getName() + "下锅,熬制半小时");
}
//持有鸡的引用 依赖
public void eat(Cock c) {
System.out.println(this.name + "吃" + c.getName());
}
}
public class Cock {
private String name;
private int weight;
public Cock(String name,int weight) {
this.name = name;
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Test {
public static void main(String[] args) {
//Person p = new Person("kaka",10,1246547658);
Person p = new Person(); // 默认构造函数
//p.setName("kaka");
// p.setAge(10);
// p.setCode(124365876);
//Person p1 = new Person("里斯",10,234235436);
Person p1 = new Person("里斯",10,234235436);
// p1.setName("jeji");
// p1.setAge(10);
// p1.setCode(13254765 );
System.out.println(p.getName() + ":" + p.getAge() + ":" + p.getCode() );
System.out.println(p1.getName() + ":" + p1.getAge() + ":" + p1.getCode() );
//对象的通讯
Person p2 = new Person("里斯",10,234235436);
Cock cc = new Cock("芦花鸡",20);
//依赖
p2.eat(cc);
//关联
p2.setC(cc);
p2.bamao();
p2.qieduqn();
p2.xiaguo();
p2.eat();
}
}