【Java】java的封装

在学习封装的时候,我首先敲了了一个关于类与对象的代码,包括两个class,一个是main程序。

main.java

public class main {

	public static void main(String[] args) {
	character character = new character();//创建角色
	character.initialization("Emue");//初始化角色
	character.showId();//输出id
	character.showName();//输出名字
	character.showGrsde();//输出等级
	character.showHP();//输出Hp
	character.showAD();//输出ad
	}

}

character.java

public class character {
	 
	public int id ;
	public String name ;
	public int grade;
	public int HP ;
	public int AD ;
	void initialization(String name)
	{
		id = 1;
		this.name = name;
		grade = 0;
		HP = 100;
		AD = 10;
	}
	void showName()
	{
		System.out.println("Your name is:"+name);
	}
	void showId()
	{
		System.out.println("Your id is:" + id);
	}
	void showHP()
	{
		System.out.print("HP:"+HP+"\t");
	}
	void showGrsde()
	{
		System.out.println("Your grade is:" + grade);
	}
	void showAD()
	{
		System.out.println("AD:" + AD);
	}
}

 Run之后,输出

Your id is:1
Your name is:Emue
Your grade is:0
HP:100	AD:10

如果这是一个游戏的话封装应该是必须的,为什么要封装呢,

很简单如果改一下代码就可以数据修改掉

main.java改为

public class main {

	public static void main(String[] args) {
	character character = new character();//创建角色
	character.initialization("Emue");//初始化角色
	character.HP=99999;
	character.showId();//输出id
	character.showName();//输出名字
	character.showGrsde();//输出等级
	character.showHP();//输出Hp
	character.showAD();//输出ad
	}

}

随后输出

Your id is:1
Your name is:Emue
Your grade is:0
HP:99999	AD:10

数据就被修改了

如果我们把数据封装一下

character.java换为

package test;

public class character {
	 
	private int id ;
	private String name ;
	private int grade;
	private int HP ;
	private int AD ;
	void initialization(String name)
	{
		id = 1;
		this.name = name;
		grade = 0;
		HP = 100;
		AD = 10;
	}
	void showName()
	{
		System.out.println("Your name is:"+name);
	}
	void showId()
	{
		System.out.println("Your id is:" + id);
	}
	void showHP()
	{
		System.out.print("HP:"+HP+"\t");
	}
	void showGrsde()
	{
		System.out.println("Your grade is:" + grade);
	}
	void showAD()
	{
		System.out.println("AD:" + AD);
	}
}

数据就不容易修改了

在运行刚才的main.java无法运行了


posted @ 2018-05-07 16:27  一生亦木  阅读(27)  评论(0编辑  收藏  举报