java 面向对象诸多小问题
1、设置类对象属性时,使用"对象名.set()"方法和"对象名.属性名"有什么区别?
Dog类
package bennett.imooc.com;
public class Dog {
String name;
int age;
float weight;
public Dog() {
}
public Dog(String name, int age, float weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
Dog测试类
package bennett.imooc.com;
public class TestDog {
public static void main(String[] args) {
Dog dog = new Dog();
dog.setName("多多");
dog.name = "多多";
dog.setAge(3);
dog.setWeight(24.5F);
System.out.println(duoduo.name);
System.out.println(dog.getName());
}
}
分析
dog.name = "多多";和set()方法中的“this.name = nam”是一样的,只是赋值策略不同罢了。
包名的命名规则