分類 | 同一個類中 | 同一個包中 | 不一樣包的子類 | 不一樣包的非子類 |
---|---|---|---|---|
private | 〇 | |||
default | 〇 | 〇 | ||
protected | 〇 | 〇 | 〇 | |
public | 〇 | 〇 | 〇 | 〇 |
class Test{ public static void main(String[] args){ Person person = new Person("Daming"); System.out.println(person.name); } } class Person{ private String name; Person(String name){ this.name = name; } public String getName(){ return this.name; } }
class Test{ public static void main(String[] args){ subPerson person = new subPerson("Daming"); } } class Person{ private String name; Person(String name){ this.name = name; } public String getName(){ return this.name; } } class subPerson extends Person{ subPerson(String name){ super(name); } public String ShowName(){ return name; } }
上訴代碼表示子類中也不能繼承private的變量。java
package com.test.Demo; class Person{ String name; Person(String name){ this.name = name; } public String getName(){ return this.name; } } public class Demo{ public static void main(String[] args){ Person person = new Person("Daming"); System.out.println(person.name); } }
上訴代碼執行的結果以下:
this
//父類的定義 package com.test.Demo; public class Person{ String name; public Person(String name){ this.name = name; } public String getName(){ return this.name; } } import com.test.Demo.Person; class Test{ public static void main(String[] args){ Person p = new Person("Daming"); System.out.println(p.name); } }
package com.lky.h1; public class Base{ private Integer id; protected String name; public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String toString(){ return "Base [id=" + id + ", name=" + name + "]"; } }
//在同一個包中的子類 package com.lky.h1; class Test1 extends Base{ public static void main(String[] args){ Test1 test1 = new Test1(); Base base = new Base(); base.name = "Daming"; test1.name = "hong"; System.out.println(base.name); System.out.println(test1.name); } }
運行結果以下:
code
package com.lky.h2; import com.lky.h1.Base; class Test2 extends Base{ public static void main(String[] args){ Test2 test2 = new Test2(); Base base = new Base(); base.name = "Daming"; test2.name = "hong"; System.out.println(base.name); System.out.println(test2.name); } }