jash.liao的JAVA整理教學:JAVA件導向-封裝與存取權限
jash.liao的JAVA整理教學:JAVA件導向–封裝與存取權限
線上執行:http://www.tutorialspoint.com/compile_java_online.php / http://www.compilejava.net/
code2html:http://tohtml.com/
修飾詞 |
類別 |
套件 |
子類別 |
所有地方 |
public |
Y |
Y |
Y |
Y |
protected |
Y |
Y |
Y |
N |
(no modifier) |
Y |
Y |
N |
N |
private |
Y |
N |
N |
N |
class Animal { privateint age; privateint weight;
publicint getAge(){ return age; } publicvoid setAge(int n){ if(n <0){ age =1; } else{ age = n; } }
publicint getWeight(){ return weight; }
publicvoid setWeight(int n){ if(n <0){ weight =1; } else{ weight = n; } }
publicvoid speak(){ System.out.println("Hello,I am "+ getAge()+" years old. I weighed "+ getWeight()+" kg"); } }
class Elephant extends Animal { privateString name;
publicString getName(){ return name; }
publicvoid setName(String n){ if(n ==null|| n.equals("")){ name ="Anonymous"; } else{ name = n; } }
publicvoid speak(){ System.out.println("My name is "+ getName()+". I am "+ getAge()+" years old"); } }
publicclass HelloWorld{
publicstaticvoid main(String[]args){ Animal puppy1 =new Animal(); puppy1.setAge(12); puppy1.setWeight(-25); puppy1.speak();
Elephant puppy2 =new Elephant(); puppy2.setAge(-8); puppy2.setWeight(1200); puppy2.setName("Elephant"); puppy2.speak(); } }
|