不同包里面的子类继承了父类却访问不了protected权限的问题

J2EE 码拜 9年前 (2015-04-22) 1097次浏览 0个评论

父类:
package father;

public class Person{
    protected void introduce(){
        System.out.println(“父类中的introduce函数,拥有protected权限”);
    }
}

子类:
package son;
import father.Person;

class Student extends Person{
    public static void main(String args []){
        Person p = new Person();
        p.introduce();
    }
}

运行后报错:
Student.java:7: 错误: introduce()可以在Person中访问protected
p.introduce();
1个错误

问题:
为什么不同包里面的子类继承了父类,却访问不了父类中protected权限的函数?

不同包里面的子类继承了父类却访问不了protected权限的问题
1分
这个确实没有遇到过,可能protected 只局限自己包内引用。。
不同包里面的子类继承了父类却访问不了protected权限的问题
5分
我感觉你是把两个问题搞混了,protected修饰,是指子类可以继承,重写,访问  ,是相当于在子类定义了该方法。
而你是实例化父类,用父类访问,是属于方法修饰符的 作用域问题。
不知你懂了没
不同包里面的子类继承了父类却访问不了protected权限的问题
5分
http://blog.csdn.net/peisl/article/details/6343386
可能我说的有点问题,protected 修饰作用域是指   1 同一个包中的类 2 子类
不同包里面的子类继承了父类却访问不了protected权限的问题
28分
改成这样:

package son;
 import father.Person;
 
class Student extends Person{
     public void myIntroduce(){
     introduce();// 这里才是“子类访问父类的protected方法”
     }
     public static void main(String args []){
         Person p = new Person();
         p.myIntroduce();
     }
 }

不同包里面的子类继承了父类却访问不了protected权限的问题
1分
class Student extends Person{
    public static void main(String args []){
       Student s = new Student();
        s.introduce();
    }
}
不同包里面的子类继承了父类却访问不了protected权限的问题
引用 2 楼 u011201384 的回复:

我感觉你是把两个问题搞混了,protected修饰,是指子类可以继承,重写,访问  ,是相当于在子类定义了该方法。
而你是实例化父类,用父类访问,是属于方法修饰符的 作用域问题。
不知你懂了没

明白啦,谢谢!

不同包里面的子类继承了父类却访问不了protected权限的问题
引用 3 楼 u011201384 的回复:

http://blog.csdn.net/peisl/article/details/6343386
可能我说的有点问题,protected 修饰作用域是指   1 同一个包中的类 2 子类

谢谢!

不同包里面的子类继承了父类却访问不了protected权限的问题
引用 4 楼 oh_Maxy 的回复:

改成这样:

package son;
 import father.Person;
 
class Student extends Person{
     public void myIntroduce(){
     introduce();// 这里才是“子类访问父类的protected方法”
     }
     public static void main(String args []){
         Person p = new Person();
         p.myIntroduce();
     }
 }

因为你的代码,使我看明白了前两楼写的文字,太感谢你了!
经过重写代码,现在可以用了!


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明不同包里面的子类继承了父类却访问不了protected权限的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!