JAVA object-oriented design pet class
need:
When designing pets, users can freely choose to raise cats or dogs, name pets, and realize the function of feeding interaction. Pets need to have satiety and happiness.
Pet class [parent class]
package ; public class Pet { String name; int full; int happy; public Pet(String name) { this(name, 50, 50); } public Pet(String name,int full,int happy) { = name; = full; = happy; } public void feed() {//How to feed pets if(full == 100) { (name+"Already full"); return; } ("Give"+name+"Feed"); full += 10; ("Satisfaction:"+full); } public void play() {//How to play with pets if(full == 0) { (name+"I'm so hungry that I can't play anymore"); return; } ("accompany"+name+"play"); happy += 10; full -= 10; ("Happiness:"+happy); ("Satisfaction:"+full); } public void punish() {//People punishment method //Different codes for subclasses, change to debugging method ( "beat"+name+"The pp,"+name+"Cry:"+cry()); happy -= 10; ("Happiness:"+happy); } public String cry() {//The little animal was beaten to cry //Senseless code //The cry() method needs to be rewritten in the subclass and returns the specific cry return "There are crying here"; } }
Kitten class [subclass]
package ; public class Cat extends Pet{ public Cat(String name, int full, int happy) { super(name, full, happy); } public Cat(String name) { super(name); } @Override public String cry() { return "Meow~"; } }
Puppy [subclass]
package ; public class Dog extends Pet { public Dog(String name, int full, int happy) { super(name, full, happy); } public Dog(String name) { super(name); } @Override public String cry() { return "Wang~"; } }
Test class
package ; import ; import ; public class TestPet { public static void main(String[] args) { ("1. Dog"); ("2. Cat"); ("Select:> "); int c = new Scanner().nextInt(); ("Give the pet a name:"); String n = new Scanner().nextLine(); //Define the cat and dog variable Dog dog = null; Cat cat = null; if(c == 1) { dog = new Dog(n); play(dog); } else { cat = new Cat(n); play(cat); } } private static void play(Dog dog) { ("Click Enter to execute"); while(true) { new Scanner().nextLine(); int r = new Random().nextInt(6); switch(r) { case 0: (); break; case 1: (); break; default: (); break; } } } private static void play(Cat cat) { ("Click Enter to execute"); while(true) { new Scanner().nextLine(); int r = new Random().nextInt(6); switch(r) { case 0: (); break; case 1: (); break; default: (); break; } } } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.