义类的时候需要包含一下组件:
私有属性
构造方法(无参构造方法和自定义构造方法)
set/get方法
普通方法
public class Dog {
private String name;
private int age;//私有属性,只能在当前类中调用
private int weight;
//构造器
public Dog(){
}
//全参构造器
public Dog(String name,int age, int weight){
this.name=name;
this.age=age;
this.weight=weight;
}
//定义一个设置年龄的方法
public void setAge(int age){
if(age>=0){
this.age=age;
}else{
System.out.println("您输入的年龄不对");
}
}
//定义一个获取年龄的方法
public int getAge(){
return this.age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight=weight;
}
//方法
public void eat(){
System.out.println("eating bones");
}
public void play(){
System.out.println("playing...");
}
public void show(){
System.out.println("name:"+this.name);
System.out.println("age:"+this.age);
System.out.println("weight:"+this.weight);
}
}