Java之关联和依赖

类之间的关系从宏观上可以分为:关联、依赖和继承。从使用频率上 关联是使用最为广泛的,其次是依赖和继承。

函数传参叫依赖。在一个类里声明另一个类的对象叫关联。关联表示一种持久的关系,而依赖关系则较为短暂。

package practice;
public class Person {
	//属性为私有
	//方法为公有
	private String name ;
	private int age ; 
	private char sex;
    private  cock c;  
	public Person() {
		this.name="Tom";
		this.age=13;
		this.sex='男';
	}
	
    public  Person(String name,int age,char sex){
		this.setName(name);
		this.setAge(age);
		this.setSex(sex);
	}
    //构造函数重载
	public void setName(String na) {
		this.name=na;
	}
	public String getName() {
		return name;
	}
	void   speak(String content) {
		System.out.println(this.name+"说:"+content);
	   }
	public void setAge(int age ) {
		if (age >0||age<=120)
			this.age=age;//this为指向堆中对象首地址的指针
		//每个this指向一个对象本身,(属性/方法)的首地址
	    }
	//接口就是函数的意思
	public int getage() {
	    return age;
	}
	//程序执行完了栈帧就没了,但相关对象的相关数据保存在堆中。
	  
	public void setSex(char sex2) {
		this.sex = sex2;
	}
     public char getSex() {
		
		return sex;
	}
	public int getAge() {
		return age;
	}
	public void maiji() {
		System.out.println("买鸡");
		
		
	}
	public  void eat(cock c) {
		System.out.println(this.name+"吃"+c.getName());
	}
	public cock getC() {
		return c;
	}
	public void setC(cock c) {
		this.c = c;
	}
}
package practice;
//实现两个对象的表白,判断性别,如果相同就不表白;
public class 	cock {
	private String  name;
	private int weight;
	cock(String name,int weight){
		this.setName(name);
		this.setWeight(weight);
	}
	public String getName() {
		return name;
	}
	public void setName(String  name) {
		this.name = name;
	}
	public int getWeight() {
		return weight;
	}
	public void setWeight(int weight) {
		this.weight = weight;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42194284/article/details/90066272