构造方法 给属性进行初始化 修改的话 原值会变成垃圾
setxxx()方法作用是修改属性值
这两种方式setxxx()用的更多更灵活
学生类的代码
public class student {
public static void main(String[] args) {
Student s1 =new Student();
s1.setAge(17);
s1.setName("zhang");
System.out.println(s1.getAge()+s1.getName());
System.out.println("_________________________");
Student s2=new Student("li",18);
s2.show();
}
}
class Student {
private String name;
private int age;
public Student() {//空参构造
}
public Student(String name,int age){//有参构造
this.name=name;
this.age=age;
}
public void setName(String name){//设置名字
this.name=name;
}
public String getName(){//获取名字
return name;
}
public void setAge(int age){//设置年龄
this.age=age;
}
public int getAge(){ //获取年龄
return age;
}
public void show(){
System.out.println(name+age);
}
}
手机类的代码
public class phone {
public static void main(String[] args){
Phone p1=new Phone();
p1.setbrand("三星");
p1.setprice(1234);
System.out.println(p1.getbrand()+p1.getprice());
System.out.println("_______________________");
Phone p2=new Phone("xiaomi",99);
p2.show();
}
}
class Phone{ //手机类
private int price; //价格
private String brand;//品牌
public Phone() {}//空参构造
public Phone(String brand,int price) { //有参构造
this.brand=brand;
this.price=price;
}
public void setbrand(String brand){
this.brand=brand;
}
public String getbrand(){
return brand;
}
public void setprice(int price) {
this.price=price;
}
public int getprice(){
return price;
}
public void show(){
System.out.println(brand+price);
}
}