将嵌套类继承到子类中

将嵌套类继承到子类中

本文介绍了将嵌套类继承到子类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我浏览文章时, 超类中的私人成员,我看到这一行

When I was going through this article, under the section Private Members in a Superclass, i saw this line

我的问题是我们如何在<$ c $中直接访问嵌套 Base c>派生(就像我们可以访问任何 public protected 字段)?

My question is how can we DIRECTLY access the Nested class of Base in Derived (like we can access any public, protected fields)?

如果有办法,怎么能派生访问 p 这是私有字段> 嵌套

if there is a way, how can Derived access p which is private field of Base through Nested?

public class Base {

    protected int f;
    private int p;

    public class Nested {

        public int getP() {
            return p;
        }
    }
}

class Derived extends Base {

    public void newMethod() {
        System.out.println(f); // i understand inheriting protected field

        // how to access the inherited Nested class here? and if accessed how to retrieve 'p' ?
    }

}

提前感谢您的时间和努力在这个线程中!

Thanks in advance for your time and effort in this thread!

推荐答案

Base.Nested theClassBro= new Base.Nested();

或者对于Derived类,这应该有效:

Or for the Derived class, this should work:

Derived.Nested theClassBro= new Derived.Nested();

我不确定你是否需要使用超级关键字

I'm not sure if you need to use the super keyword or not

这篇关于将嵌套类继承到子类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:43