(1)能夠繼承父類的public和PRotected變量.不能夠繼承父類的private變量;
package test1;class son{ public int a; protected int b; int c; private int d; public son(){}}public class a extends son{ @Override public String toString() { // TODO Auto-generated method stub String temp = ""; temp += a; temp += b; temp += c;// temp += d; 錯誤,private不能繼承 return temp; } public static void main(String[] args) { a o = new a(); System.out.println(o); }}/* * 輸出:000 */(2)對于父類的包訪問權限變量,如果子類和父類在同一個包下,則子類能夠繼承;否則,子類就不能夠繼承;
package test2;import test1.son;public class b extends son{ @Override public String toString() { // TODO Auto-generated method stub String temp = ""; temp += a; temp += b;// temp += c; 錯誤 包訪問權限只能在同一個包內繼承// temp += d; 錯誤 private訪問權限只能在本類使用,不能繼承 return temp; } public static void main(String[] args) { b o = new b(); System.out.println(o); }}/* * 輸出:00 */方法原則:(1)能夠繼承父類的public和protected方法.不能夠繼承父類的private方法;package test1;public class son { public son(){} public void fun1(){ System.out.println("son.fun1()"); } public static void fun1_s(){ System.out.println("son.fun1_s()"); } protected void fun2(){ System.out.println("son.fun2()"); } protected static void fun2_s(){ System.out.println("son.fun2_s()"); } void fun3(){ System.out.println("son.fun3()"); } static void fun3_s(){ System.out.println("son.fun3_s()"); } private void fun4(){ System.out.println("son.fun4()"); } private void fun4_s(){ System.out.println("son.fun4_s()"); }}package test1;/** * 同一個包內 * @author ziwang * */public class a extends son{ private void show() { // TODO Auto-generated method stub this.fun1(); a.fun1_s(); this.fun2(); a.fun2_s(); this.fun3(); a.fun3_s();// this.fun4(); 錯誤,private方法只能自己類使用,不能繼承// a.fun4_s(); 錯誤,private方法只能自己類使用,不能繼承 } public static void main(String[] args) { a o = new a(); o.show(); }}/* * 輸出: * son.fun1() son.fun1_s() son.fun2() son.fun2_s() son.fun3() son.fun3_s() */(2)對于父類的包訪問權限方法,如果子類和父類在用一個包下,則子類能夠繼承;否則,子類就不能夠繼承;
package test2;import test1.son;public class b extends son{ private void show() { // TODO Auto-generated method stub fun1(); b.fun1_s(); fun2(); b.fun2_s();// fun3(); 錯誤,包訪問權限只有在同一個包內才可以繼承// b.fun3_s(); 錯誤,包訪問權限只有在同一個包內才可以繼承// fun4(); 錯誤,private不能繼承// b.fun4_s(); 錯誤,private不能繼承 } public static void main(String[] args) { b o = new b(); o.show(); }}/* * 輸出: * son.fun1() son.fun1_s() son.fun2() son.fun2_s() */
新聞熱點
疑難解答