• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

在学生子类Student中访问父类Person成员。protected关键字使用

package com;
class Person {
    protected String name;
    protected int age;//声明被保护成员变量

    public Person() {
        System.out.println("调用了Person类的无参构造方法");
    }

    public Person(String name, int age) {
        System.out.println("调用了Person类的有参构造方法");
        this.name = name;
        this.age = age;
    }

    public void show() {
        System.out.println("姓名" + name + "年龄" + age);
    }
}
class Student extends Person
    {
        private String department;
        public Student()
        {
            System.out.println("调用了Student类的无参构造方法");
        }
        public Student(String xm,int age,String dep)
        {
            name=xm;//在子类直接访问父类的成员变量
            this.age=age;
            super.show();
            //调用父类的有参构造方法 public Person(String name,int age)
            department=dep;
            System.out.println("我是"+department+"的学生");
            System.out.println("调用了Student类的有参构造方法Student(String name,int age,String dep)");
        }
    }

public class app8_2 {
    public static void main(String[] args)
    {

        Student stu1=new Student();//创建对象,并调用无参构造方法
        Student stu2=new Student("李小四",23,"信息系");//创建对象,并调用有参构造方法

        stu1.show();
        stu2.show();

    }

}

输出

 

 protected String name;
 protected int age;//声明被保护成员变量

子类无法继承父类的private成员,所以无法在子类中(类外)访问父类中的这种成员,但如果将父类中的成员声明为protected成员的,而非private成员,则不仅可以在父类中直接访问,同样也可以在其子类中访问。

声明为protected成员,只能供父类与子类或者同一包中的类来访问,而其他类则无法访问它。

posted on 2022-04-12 20:02  王陈锋  阅读(64)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3