1 package com.example; 2 3 /** 4 * Created by Y on 16/4/13. 5 */ 6 public class Person { 7 private int age; 8 private String name; 9 public int getAge() { 10 return age; 11 } 12 13 public void setAge(int age) { 14 if (age>=0 && age<=150) { 15 this.age = age; 16 } 17 } 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 public void tell(){ 27 System.out.println("年龄是:" + getAge() + "姓名是:" + getName()); 28 } 29 30 }
1 package com.example; 2 3 4 public class MyClass { 5 public static void main(String[] args){ 6 //封装性:保护某些属性和方法不被外部所看见.为属性和方法进行封装是通过关键字PRIVATE声明的.实现该属性的SET和GET方法为外部所访问 7 Person per = new Person(); 8 per.setName("xiaoyu"); 9 per.setAge(20); 10 per.tell(); 11 } 12 }