构造与封装
构造器的使用
package com. hyb. oop. D2;
public class Constructor {
public String name;
public int age;
public Constructor ( ) {
this . name= "huangyubin" ;
this . age= 20 ;
}
public Constructor ( String name, int age) {
this . name = name;
this . age= age;
}
}
package com. hyb. oop. D1;
import com. hyb. oop. D2. Constructor;
public class makeoop {
public static void main ( String[ ] args) {
Constructor constructor = new Constructor ( ) ;
System. out. println ( constructor. name) ;
System. out. println ( constructor. age) ;
}
}
封装
package com. hyb. oop. D3;
public class Encapsulation {
private int age;
private String name;
public int getAge ( ) {
return age;
}
public void setAge ( int age) {
if ( age> 0 && age<= 100 ) {
this . age = age;
} else {
this . age= 3 ;
}
}
}
package com. hyb. oop. D1;
import com. hyb. oop. D3. Encapsulation;
public class makeoop {
public static void main ( String[ ] args) {
Encapsulation encapsulation = new Encapsulation ( ) ;
encapsulation. setAge ( - 10 ) ;
System. out. println ( encapsulation. getAge ( ) ) ;
}
}