Dog class
1 /***2 * pet dog class, encapsulated with permission modifier private and public3 * @authorChenyanlong4 * Date: 2017/10/155 */6 Packagecom.hp.test07;7 8 Public classDog {9 Ten //Defining Variables One PrivateString name;//Nickname A Private intHealth//Health Value - Private intLove//Degree of intimacy - PrivateString strain;//set the breed of dog the - - /*increase health value by eating*/ - Public voideat () { + if(health>=100){ -System.out.println ("Dog" +name+ "needs exercise"); +}Else{ AHealth=health+5; atSystem.out.println ("Master," +name+ "ate!") "); - } - } - - /*increase intimacy by playing games with the host, but at the same time reducing health values*/ - Public voidPlay () { in if(health<20){ -System.out.println ("Master," +name+ "sick."); to}Else{ +Health=health-3; -Love=love+5; the } * } $ PublicString GetName () {Panax Notoginseng returnname; - } the Public voidsetName (String name) { + This. Name =name; A } the Public intGethealth () { + returnHealth ; - } $ Public voidSethealth (intHealth ) { $ This. Health =Health ; - } - Public intGetlove () { the returnLove ; - }Wuyi Public voidSetlove (intLove ) { the This. Love =Love ; - } Wu - About PublicString Getstrain () { $ returnstrain; - } - - Public voidSetstrain (String strain) { A This. Strain =strain; + } the - @Override $ PublicString toString () { the return"Dog [name=" + name + ", health=" + health + ", love=" + Love + ", strain=" + Strain + "]"; the } the the - in}
Dogtest class:
Packagecom.hp.test07;ImportJava.util.Scanner; Public classDogtest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubDog dog=NewDog (); System.out.println ("----------------Welcome to the Pet shop--------------"); System.out.println ("Please select a pet species to adopt: 1. Pug 2. Shepherd Dog"); Scanner input=NewScanner (system.in); Dog.setstrain (Input.nextline ()); System.out.println ("Please give your dog a nice name:"); Scanner INPUT1=NewScanner (system.in); Dog.setname (Input1.next ()); System.out.println ("Set Health value: eg:80"); Scanner Input2=NewScanner (system.in); Dog.sethealth (Input2.nextint ()); System.out.println ("Set Heart value: Eg:80"); Scanner INPUT3=NewScanner (system.in); Dog.setlove (Input3.nextint ()); System.out.println (Dog.tostring ()); }}
Operating effect:
Java code example (7-1)