[Java class package]

Package

UseprivateTo achieve encapsulation processing member properties.
The most important feature of the package isThe internal structure is not visible outside
----------------------------------------------

Package implemented using private :

class Person {
	//定义成员变量
	private String name;
	private int age;
	//定义成员方法
	public void tell() {
		System.out.println("姓名:" + name + "、年龄:" + age);
	}

	//setter()和getter()方法
	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 class Demo {
	public static void main(String[] args) {
		Person p = new Person();
		p.setName("张三");
		p.setAge(-18);
		per.tell();
	}
}

This procedure using the private keyword package implements the Person class member variables, name and age for such use can only be defined in the Person class. If you want to modify the content of external operation member variables of an object must pass setter () or getter () method call.

Published 38 original articles · won praise 4 · Views 831

Guess you like

Origin blog.csdn.net/Hide111/article/details/104974611