设计猫类:
1.确定类的属性:首先要确定猫类的属性,比如种类,颜色,年龄和体重等。这些属性将成为猫类对象的特征。
2.确定类的行为:考虑猫的行为,比如喵叫、玩游戏等。这些行为将成为猫类对象可以执行的方法。
3.创建类:在面向对象的编程语言中,通过关键字 class 创建一个类。(注意要有无参构造方法)
4.实例化对象:通过类创建具体的对象,这些对象将拥有类所定义的属性和方法。
5.使用对象:通过对象调用类定义的方法,或者获取对象的属性。
package com.cat.java;
public class Cat {
String category;//种类
String color;//颜色
int age;
double weight;
public Cat(){//无参构造方法
}
public Cat(String name,String color,int age,double weight){
//有参构造方法
this.category = category;
this.color = color;
this.age = age;
this.weight = weight;
}
//setter,getter方法
//set方法:给成员变量赋值
//get方法:对外提供成员变量的值
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
//输出猫的信息的方法
public void printCat(){
System.out.println("种类:" + this.category);
System.out.println("颜色:" + this.color);
System.out.println("年龄:" + this.age + " years old");
System.out.println("体重:" + this.weight + " kg");
}
//猫发出叫声
public void makeSound(){
System.out.println("mewo!!!");
}
//猫玩玩具
public void catPlay(String toy){
System.out.println("The cat is playing with " + toy);
}
}
package com.cat;
import com.cat.java.Cat;
public class Demo005 {
public static void main(String[] args) {
Cat myCat = new Cat("Siamese", "Brown", 3, 4.5);
myCat.printCat();
myCat.makeSound();
myCat.catPlay("a ball of yarn");
}
}
结果展示: