Java封装概述

时间:2021-01-28 21:34:22

1.封装概述

  private

   public

2.实现封装

例子:

package com.java1995;

public class Student {
private String name;
private String sex;
private int age;

public String getName(){
return name;
}

public void setName(String name){
this.name=name;
}

public String getSex() {
return sex;
}

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

public int getAge() {
return age;
}

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

package com.java1995;

public class Time {
private int hour;
private int minute;
private int second;
public int getHour() {
return hour;
}
public void setHour(int hour) {
if(hour>24||hour<0){
this.hour=-1;
}
else
this.hour = hour;
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
}
public void Look(Time t){
if(t.getHour()==-1)
System.out.println("输入有误!");
else
System.out.println(t.getHour());
}
}

package com.java1995;

public class Test {
public static void main(String[] args){
Student s=new Student();
s.setName("Mike");
System.out.println("姓名"+s.getName());

Time t =new Time();
t.setHour(25);
t.setMinute(22);
t.setSecond(34);
t.Look(t);
}

}