To create a dog class:
1 /**2 * Dog Class3 * @authorAdministrator4 *5 */6 Public classDog {7String name= "Anonymous";//name8 inthealth=0;//Health Value9 intlove=0;//Degree of intimacyTenString strain= "smart Labrador Retriever";//Variety One A /** - * Output Dog information - */ the Public voidprint () { -System.out.println ("Pet confession: \ n My Name" + This. name+ ", health value is" + This. health+ ", pro density =" + This. love+ "I am a" + This. strain); - } -}
To create a penguin class:
1 /**2 * Penguin class, using static constants3 * @authorAdministrator4 *5 */6 Public classPenguin {7String name= "Anonymous";//name8 inthealth=0;//Health Value9 intlove=0;//Degree of intimacyTen FinalString sex_male= "Q Tsai"; One FinalString sex_female= "Q sister"; AString Sex=sex_male;//Sex - - Public voidprint () { theSystem.out.println ("Pet confession: \ n My Name" + This. name+ ", health value is" + This. health+ ", pro density =" + This. love+ ", I am a" + This. Sex); - } -}
To create specific pet object information by testing the class:
1 ImportJava.util.*;2 Public classTest {3 Public Static voidMain (string[] args) {4Scanner input=NewScanner (system.in);5System.out.println ("Welcome to the Pet Shop");6System.out.println ("Please enter the name of the pet to be adopted:");7String name=Input.next ();8SYSTEM.OUT.PRINTLN ("Please select the type of pet to adopt: (1. Dog 2. Penguin)");9 intCoolse=input.nextint ();Ten Switch(coolse) { One Case1: A //Choose your dog -SYSTEM.OUT.PRINTLN ("Choose your Dog's breed: (1. Smart Labrador 2. Cool Snow Schnauzer)"); -String strain=NULL; the if(Input.nextint () ==1) { -strain= "Smart Labrador Dog"; - } - Else{ +Strain= "Cool Snow schnauzer"; - } + //Create a Dog object and assign a value ADog dog=NewDog (); atDog.name=name; -dog.health=100; -dog.love=100; -dog.strain=strain; - dog.print (); - Break; in Case2: - //Choose Penguin toSYSTEM.OUT.PRINTLN ("Please select Penguin Sex: (1.Q 2.Q sister)"); +String sex=NULL; - if(Input.nextint () ==1) { thesex= "Q Tsai"; * } $ Else{Panax Notoginsengsex= "Q Sister"; - } the //Create a Penguin object and assign a value +Penguin pg=NewPenguin (); APg.name=name; thepg.sex=sex; +pg.health=100; -pg.love=100; $ pg.print (); $ Break; - default: -System.out.println ("Please enter the correct option"); the Break; - }Wuyi } the -}
Execution results such as:
Classes and objects in Java