public class Dog { private String name; private String type; //构造器 public Dog( String type) { this.type = type; } public Dog() { } //get和set方法 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; } }
--------------------------------------------------------- import java.util.Scanner; /** * 人类 * 属性 * 姓名 * 拥有宠物狗 * * 行为 * 领养狗 * 给狗起名字 * 介绍自己的宠物狗 */ public class Person { private String name; private Dog dog; public void adopDog(Dog dog){ System.out.println(this.name+"领养了"+dog.getType()+"品种的狗"); this.dog=dog; } public void giveName(){ if(this.dog==null){ System.out.println("领养一条狗"); return; } System.out.println("请输入狗的新名字"); String dogName =new Scanner(System.in).next(); this.dog.setName(dogName); } public void say(){ System.out.println("我叫"+name+",我有一条"+this.dog.getType()); System.out.println("品种的宠物狗,名字叫"+this.dog.getName()); } public Person(String name) { this.name = name; } public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } }
-----------------------------------------------------------------------------------------------
测试类 public class Test { public static void main(String[] args) { Dog d1= new Dog("中华田园犬"); Dog d2= new Dog("哈士奇"); Person p1= new Person("某人"); Person p2= new Person("x某人"); p1.adopDog(d2); p1.giveName(); p1.say(); } }