如何在其子类中访问类的私有变量? [英] How to access the private variables of a class in its subclass?

查看:109
本文介绍了如何在其子类中访问类的私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在接受采访时被问到的问题:我有A级私人成员,B级扩展A.我知道一个班级的私人成员无法访问,但问题是:我需要访问私人成员B类中的A类,而不是在B类中创建具有相同值的变量。

This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the question is: I need to access private members of class A from class B, rather than create variables with the same value in class B.

推荐答案

面试官要么测试你的知识访问修饰符,或您更改现有类的方法,或两者​​兼而有之。

The interviewer was either testing your knowledge of access modifiers, or your approach to changing existing classes, or both.

我会列出它们(公共,私有,受保护,包私有)以及每个类的解释。然后继续说A类需要被修改以允许通过添加setter和getter,或者通过更改成员的访问修饰符来访问B类中的那些成员。或者B类可以使用反射。最后,谈谈每种方法的优缺点。

I would have listed them (public, private, protected, package private) with an explanation of each. Then gone on to say that class A would need to be modified to allow access to those members from class B, either by adding setters and getters, or by changing the access modifiers of the members. Or class B could use reflection. Finally, talk about the pros and cons of each approach.

这篇关于如何在其子类中访问类的私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆