首页 > 学院 > 开发设计 > 正文

继承访问权限

2019-11-11 02:20:13
字体:
来源:转载
供稿:网友
当子类继承了某个类后,便可以使用父类中的成员变量,当并不是完全继承父类的所有成员变量,具体原则如下变量原则:

(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() */


上一篇:IoBuffer

下一篇:图的深度优先遍历

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表