java的类和对象

时间:2023-03-08 17:54:16

创建狗狗类:

 /**
* 狗狗类
* @author Administrator
*
*/
public class Dog {
String name="无名氏"; //姓名
int health=0; //健康值
int love=0; //亲密度度
String strain="聪明的拉布拉多犬"; //品种 /**
* 输出狗狗信息
*/
public void print(){
System.out.println("宠物自白:\n我的名字叫"+this.name+",健康值为"+this.health+",亲密度为"+this.love+"我是一只"+this.strain);
}
}

创建企鹅类:

 /**
* 企鹅类,使用静态常量
* @author Administrator
*
*/
public class Penguin {
String name="无名氏"; //名字
int health=0; //健康值
int love=0; //亲密度
final String SEX_MALE="Q仔";
final String SEX_FEMALE="Q妹";
String sex=SEX_MALE; //性别 public void print(){
System.out.println("宠物自白:\n我的名字叫"+this.name+",健康值为"+this.health+",亲密度为"+this.love+",我是一只" +this.sex);
}
}

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

 import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("欢迎您来到宠物店");
System.out.println("请输入要领养的宠物名字:");
String name=input.next();
System.out.println("请选择要领养的宠物类型:(1.狗狗 2.企鹅)");
int coolse=input.nextInt();
switch (coolse) {
case 1:
//选择狗狗
System.out.println("请选择狗狗的品种:(1.聪明的拉布拉多犬 2.酷酷的雪纳瑞)");
String strain=null;
if (input.nextInt()==1) {
strain="聪明的拉布拉多犬";
}
else{
strain="酷酷的雪纳瑞";
}
//创建狗狗对象并赋值
Dog dog=new Dog();
dog.name=name;
dog.health=100;
dog.love=100;
dog.strain=strain;
dog.print();
break;
case 2:
//选择企鹅
System.out.println("请选择企鹅的性别:(1.Q仔 2.Q妹)");
String sex=null;
if (input.nextInt()==1) {
sex="Q仔";
}
else{
sex="Q妹";
}
//创建企鹅对象并赋值
Penguin pg=new Penguin();
pg.name=name;
pg.sex=sex;
pg.health=100;
pg.love=100;
pg.print();
break;
default:
System.out.println("请输入正确的选项");
break;
}
} }

执行结果如下图:

java的类和对象