封装

封装

实例化一个类对象的时候要对这个类对象的属性进行赋值并输出,但,为了保证类对象的私密性,要类对象的前面用private 修饰,加了private之后就要用set()和get()方法

set()传入
get()输出
public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}
快捷键insert+alt,generate中Getter and Setter

public class TestDemo {
public static void main(String[] args) {
Person person=new Person();
person.setOccupation(“teacher”);
person.setAge(18);
person.setName(“张三”);
System.out.println(“姓名”+person.getName()+",年龄:"+person.getAge());

}

}
class Person{
private String occupation;
private String name;
private int age;

public void setOccupation(String occupation) {
    this.occupation = occupation;
}

public String getOccupation() {
    return occupation;
}

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;
}

}

结果
姓名:张三,年龄:18职业:teacher

你可能感兴趣的:(封装)