类与对象之类的封装

1.所谓类的封装是指将其属性私有化(用private关键字),这样外界不能直接访问成员变量

2,如何访问?

提供获取属性的getXxx方法和设置属性值的setXxx方法

例:

package cn.sd.jsj;

public class PersonTest
{

	public static void main(String[] args)
	{
		Person  person=new  Person();
		person.name="张鹏";
		person.sex="男";
		person.age=23;
		person.say();
		
	}

}
class  Person
{
	String  name;
	String  sex;
	int  age;
	public  void  say()
	{
		System.out.println("I  am  "+name+", I  am  "+age+"  ,I  am "+age+"years  old");
	}

}

结果:I  am  张鹏, I  am  23  ,I  am 23years  old

package cn.sd.jsj;

public class PersonTest
{

	public static void main(String[] args)
	{
		Person  person=new  Person();
		//person.name="张鹏";
		person.setName("张鹏");
		//person.sex="男";
		person.setSex("男");
		//person.age=23;
		person.setAge(23);
		person.say();
		
	}

}
class  Person
{
	private  String  name;
	private  String  sex;
	private  int  age;
	
	
	public void setName(String name) 
	{
		this.name = name;
	}


	public void setSex(String sex)
	{
		this.sex = sex;
	}


	public void setAge(int age)
	{
		this.age = age;
	}


	public  void  say()
	{
		System.out.println("I  am  "+name+", I  am  "+age+"  ,I  am "+age+"years  old");
	}

}

例:

package cn.sd.jsj;

public class PersonTest
{

	public static void main(String[] args)
	{
		Person  person=new  Person();
		//person.name="张鹏";
		person.setName("张鹏");
		//person.sex="男";
		person.setSex("男");
		//person.age=23;
		person.setAge(23);
		System.out.println(person.getName());
		person.say();
		
	}

}
class  Person
{
	private  String  name;
	private  String  sex;
	private  int  age;
	
	
	public void setName(String name) 
	{
		this.name = name;
	}


	public void setSex(String sex)
	{
		this.sex = sex;
	}


	public void setAge(int age)
	{
		this.age = age;
	}
	

	public String getName() {
		return   this.name;
	}


	public  void  say()
	{
		System.out.println("I  am  "+name+", I  am  "+age+"  ,I  am "+age+"years  old");
	}

}

输出:

张鹏

I  am  张鹏, I  am  23  ,I  am 23years  old

例二:

package cn.sd.jsj;
public class PersonTest
{
	public static void main(String[] args)
	{
		Person  person1,person2;
		person1=new  Person();
		person2=new  Person();
		person1.setAbove(12.0f);
		person1.setBottom(23.1f);
		person1.setHeight(3.4f);
		System.out.println(person1.computerArea());
		person2.setAbove(3.6f);
		person2.setBottom(3.4f);
		person2.setHeight(1.2f);
		System.out.println(person2.computerArea());
	}
}
class  Person
{
	private  float  above;
	private  float  bottom;
	private  float  height;
	public float getAbove() {
		return above;
	}
	public void setAbove(float above) {
		this.above = above;
	}
	public float getBottom() {
		return bottom;
	}
	public void setBottom(float bottom) {
		this.bottom = bottom;
	}
	public float getHeight() {
		return height;
	}
	public void setHeight(float height) {
		this.height = height;
	}
	public  float  computerArea()
	{
		return  (above+bottom)*height/2.0f;
	}
	
}

猜你喜欢

转载自blog.csdn.net/zyxzyxzyx2495310073/article/details/80224247