封装性
package com.www.java;
/*
* 面向对象的特征一:封装与隐藏
*
*/
public class AnimalTest {
public static void main(String[] args) {
Animal a = new Animal();
a.name = "花花";
a.age = 1;
//a.legs = 4;//The field Animal.legs is not visible
a.show();
a.setLegs(6);
a.show();
}
}
class Animal{
String name;
int age;
private int legs;//避免用户调用此属性(有些贱兮兮的非要给猪崽子-4条腿)
public void setLegs(int i) {
if(i > 0) {
legs = i;
}else {
legs = 0;
}
}
public int getLegs() {
return legs;
}
public void eat() {
System.out.println("动物进食");
}
public void show() {
System.out.println("名字:"+name+",年龄:"+age+",腿:"+legs);
}
}
package com.www.java;
public class Order {
private int orderPrivate;
int orderDefault;
public int orderPublic;
private void methodPrivate() {
orderPrivate = 1;
orderDefault = 2;
orderPublic = 3;
}
void methodDefault() {
orderPrivate = 1;
orderDefault = 2;
orderPublic = 3;
}
public void methodPublic() {
orderPrivate = 1;
orderDefault = 2;
orderPublic = 3;
}
}
package com.www.java;
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
order.orderDefault = 1;
order.orderPublic = 2;
//出了order类后,私有结构无法使用
//order.orderPrivate = 3;The field Order.orderPrivate is not visible
order.methodDefault();
order.methodPublic();
//order.methodPrivate();The method methodPrivate() from the type Order is not visible
}
}
package com.wuww.java;
import com.www.java.Order;
public class OrderTest {
public static void main(String[] args) {
Order order = new Order();
order.orderPublic = 2;
//出了所属包后,私有结构、缺省结构无法调用
//order.orderDefault = 1;The field Order.orderDefault is not visible
//order.orderPrivate = 3;The field Order.orderPrivate is not visible
order.methodPublic();
//order.methodDefault();The method methodDefault() from the type Order is not visible
//order.methodPrivate();The method methodPrivate() from the type Order is not visible
}
}
练习
package com.www.java;
public class Person {
private int age;
void setAges(int a) {
if(a < 0 || a > 130) {
System.out.println("非法年龄");
return;
}
age = a;
}
int getAges() {
return age;
}
}
package com.www.java;
public class PersonTest {
public static void main(String[] args) {
Person p = new Person();
p.setAges(150);
System.out.println(p.getAges());
}
}