package come.lovejava;
public class Person
{
String name;
int age;
public void speak()
{
System.out.println("我叫"+name+"今年我"+age+"岁了!");
}
}
测试类
package come.lovejava;
public class PersonTest
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Person per=new Person();
per.name="张三";
per.age=-18;
per.speak();
}
}
年龄为负数,显然是不对的,不允许外界随意访问,这就需要实现类的封装。
如何实现类的封装?
package come.lovejava;
public class Person
{
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
if(age<=0)
{
System.out.println("您输入的年龄不对!");
}
else
{
this.age = age;
}
}
public void speak()
{
System.out.println("我叫"+name+"今年我"+age+"岁了!");
}
}
测试类如下
package come.lovejava;
public class PersonTest
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Person per=new Person();
//不允许直接调用,故提供了相关接口
per.setName("张三");
per.setAge(-18);
per.speak();
}
}
因为name是私有的,故不能直接调用,这里报错。