package cn.hp.demo;
public class Dog {
private String name;
private String type;
public Dog(){
}
public Dog(String type){
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
package cn.hp.demo;
public class DogTest {
public static void main(String[] args) {
//创建几个宠物狗()
Dog d1 = new Dog("中华田园犬");
Dog d2 = new Dog("哈士奇");
Dog d3 = new Dog("萨摩耶");
Dog d4 = new Dog("边牧");
Dog d5 = new Dog("藏獒");
//创建人类
Person p1 = new Person("马子伟");
Person p2 = new Person("高金良");
//领养狗
p1.adoptDog(d2);
p1.givename();
p1.say();
p2.adoptDog(d3);
p2.givename();
p1.say();
}
}
package cn.hp.demo;
import java.lang.reflect.Type;
import java.util.Scanner;
/*
*人类
* 属性
* 姓名
* 拥有宠物狗
* 行为
* 领养狗
* 给狗起名字
* 介绍自己的宠物
*/
public class Person {
private String name;
private Dog dog;
/*
* 文档注释
* */
public void adoptDog(Dog dog){
System.out.println(this.name+"领养了"+dog.getType()+"品种的狗");
//把要领养的狗,设置到人类属性中才算领养
this.dog=dog;
}
/*
* 给宠物狗起名字
* */
public void givename(){
System.out.println("请输入宠物狗的名字");
String dogName = new Scanner(System.in).next();
//this.dog就代表当前这个人类的宠物狗属性
this.dog.setName(dogName);
}
/*
* 介绍自己的宠物狗
* */
public void say(){
System.out.println("我叫"+name+"我有一条"+this.dog.getType());
System.out.println("品种的宠物狗,名字叫"+this.dog.getName());
}
//构造器
public Person(String type){
this.name = type;
}
public void setName(String name) {
this.name = name;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public Dog getDog() {
return dog;
}
}