private和Getter/Setter方法的关系

如果用private修饰一个类的属性,当子类访问此属性时,不能直接用点的方式来访问此属性,可以通过Getter和Setter的方法来对此属性进行操作。用private修饰属性的原因是为了防止其他不合法的操作,所以我们通常会在setter方法里面写一些判断的条件,来达到目的。例如,下面的栗子:

package com.oracle;

public class Person01 {
	String name;
	private int age;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		if(age>0){
			this.age = age;	
		}
	}
}
发布了42 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43668119/article/details/104291229