一、自定义类动物,属性:名字年龄颜色,行为:吃跑睡觉,创建赋值调用
Pet
public class Pet {
String name;
int age;
String color;
public void eat() {
System.out.println("吃");
}
public void run() {
System.out.println("跑");
}
public void sleep() {
System.out.println("睡觉");
}
}
Test01
public class Test01 {
public static void main(String[] args) {
Pet pet = new Pet();
pet.name = "孬孬";
pet.age = 18;
pet.color = "黄色";
System.out.println(pet.age + pet.name + pet.color);
pet.eat();
pet.run();
pet.sleep();
}
}
二、定义Person类,属性:姓名年龄,方法:显示属性;定义一个数组存储3个Person,键盘录入属性后遍历Person方法。
Person
public class Person {
String name;
int age;
public void show(){
System.out.println(name+age);
}
}
Test02
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
Person[] people= new Person[3];
Scanner scanner=new Scanner(System.in);
for (int i=0;i<3;i++){
System.out.println("输入第"+(i+1)+"个人的名字");
String name=scanner.next();
System.out.println("输入第"+(i+1)+"个人的年龄");
int age=scanner.nextInt();
Person person=new Person();
person.name=name;
person.age=age;
people[i]=person;
}
for (int j=0;j<people.length;j++){
Person per=people[j];
per.show();
}
}
}