java的类和对象

创建狗狗类:

 1 /**
 2  * 狗狗类
 3  * @author Administrator
 4  *
 5  */
 6 public class Dog {
 7     String name="无名氏";  //姓名
 8     int health=0;        //健康值
 9     int love=0;        //亲密度度
10     String strain="聪明的拉布拉多犬";   //品种
11     
12     /**
13      * 输出狗狗信息
14      */
15     public void print(){
16         System.out.println("宠物自白:
我的名字叫"+this.name+",健康值为"+this.health+",亲密度为"+this.love+"我是一只"+this.strain);
17     }
18 }

创建企鹅类:

 1 /**
 2  * 企鹅类,使用静态常量
 3  * @author Administrator
 4  *
 5  */
 6 public class Penguin {
 7     String name="无名氏";   //名字
 8     int health=0;       //健康值
 9     int love=0;        //亲密度
10     final String SEX_MALE="Q仔";  
11     final String SEX_FEMALE="Q妹";
12     String sex=SEX_MALE;   //性别
13 
14     public void print(){
15         System.out.println("宠物自白:
我的名字叫"+this.name+",健康值为"+this.health+",亲密度为"+this.love+",我是一只" +this.sex);
16     }
17    }

通过测试类来创建具体的宠物对象信息:

 1 import java.util.*;
 2 public class Test {
 3     public static void main(String[] args) {
 4         Scanner input=new Scanner(System.in);
 5         System.out.println("欢迎您来到宠物店");
 6         System.out.println("请输入要领养的宠物名字:");
 7         String name=input.next();
 8         System.out.println("请选择要领养的宠物类型:(1.狗狗  2.企鹅)");
 9         int coolse=input.nextInt();
10         switch (coolse) {
11         case 1:
12             //选择狗狗
13             System.out.println("请选择狗狗的品种:(1.聪明的拉布拉多犬 2.酷酷的雪纳瑞)");
14             String strain=null;
15             if (input.nextInt()==1) {
16                 strain="聪明的拉布拉多犬";
17             }
18             else{
19                 strain="酷酷的雪纳瑞";
20             }
21             //创建狗狗对象并赋值
22             Dog dog=new Dog();
23             dog.name=name;
24             dog.health=100;
25             dog.love=100;
26             dog.strain=strain;
27             dog.print();
28             break;
29         case 2:
30             //选择企鹅
31             System.out.println("请选择企鹅的性别:(1.Q仔  2.Q妹)");
32             String sex=null;
33             if (input.nextInt()==1) {
34                 sex="Q仔";
35             }
36             else{
37                 sex="Q妹";
38             }
39             //创建企鹅对象并赋值
40             Penguin pg=new Penguin();
41             pg.name=name;
42             pg.sex=sex;
43             pg.health=100;
44             pg.love=100;
45             pg.print();
46             break;
47         default:
48             System.out.println("请输入正确的选项");
49             break;
50         }
51     }
52 
53 }

执行结果如下图:

原文地址:https://www.cnblogs.com/liutao1122/p/6595788.html