JavaSE-Inheritance of Three Object-Oriented Features (8)

1. Problems in current procedures
无法保证数据的安全性,同时也无法保证数据的有效性

demo:Insert picture description here

2. Packaging requirements

1.private: private, content modified by private can only be used inside the class

2. Provide public get/set methods for private attributes

  • Assign value to the attribute: set method
    public void set attribute name (data type variable name) {         this. attribute name = variable name; } Note: set attribute name--"the first letter of the attribute name is capitalized and the           parameter data type depends on the attribute data assigned Types of



  • Get the attribute value: get method
    public data type get attribute name (){        return this. attribute name; // this. can be omitted } Note: get attribute name—"the first letter of the attribute name is capitalized . The data type of the return value depends on the accessed attribute type of data




    Insert picture description here
public class TestStudent2{
    
    
 public static void main(String[] args){
    
    
  Student s = new Student();
  //s.name = "赵旭";
  s.setName("赵旭");
  //s.age = 380;
  // 外界为私有化的属性赋值:set
  s.setAge(38);
  //s.score = 99.0;
  s.setScore(99.0);
  // 访问私有的属性时:get
  System.out.println(s.getName()+"\t"+s.getAge()+"\t"+s.getScore());
  Student s2 = new Student("张飞",999,89.0);
  System.out.println(s2.getName()+"\t"+s2.getAge()+"\t"+
              s2.getScore());
 }
}
class Student{
    
    
 private String name;
 private int age; // 0~200
 private double score;// 0~100
 
 public Student(){
    
    }
 public Student(String name,int age,double score){
    
    
  this.name = name;
  //this.age = age;
  setAge(age);
  //this.score = score;
  setScore(score);
 }
 
 // set:为私有属性赋值(0~150)
 public void setAge(int age){
    
    
  // 进行数据有效性检测
  if(age>=0 && age <=150){
    
    
   this.age = age;
  }else{
    
    
   System.out.println("年龄数据无效~");
  }
 }
 // get:获取私有属性的值
 public int getAge(){
    
    
  return this.age; //this. 可以省略
 }
 // name : set
 public void setName(String name){
    
    
  this.name=name;
 }
 public String getName(){
    
    
  return this.name;
 }
 
 // score
 public double getScore(){
    
    
  return this.score;
 }
 public void setScore(double score){
    
    
  if(score>=0 && score<=100){
    
    
   this.score=score;
  }else{
    
    
   System.out.println("分数输入有误...");
  }
 }
}
Three, the meaning of encapsulation
  • Protect the security of data, and can check the validity of the data
  • Only provide corresponding functions externally, but shield the details of specific implementation
Four, package summary
  • Attribute privatization: private modifier attribute
  • Provide public get/set methods for privatized attributes

Guess you like

Origin blog.csdn.net/Java_lover_zpark/article/details/104851264