Java:你如何访问两个级别的父类方法? [英] Java: How do you access a parent class method two levels down?

查看:243
本文介绍了Java:你如何访问两个级别的父类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它扩展了我需要覆盖的类,但我需要调用该类的父类。既然我不能打电话给super,因为那会执行直接父母什么是获得父类父母的最佳方式?

I have a class that extends a class that I need to overide, but I need to call that class's parent class. since I can't call super since that will execute the direct parent what is the best way to get the parent of my parent class?

我确信这是一个基本的问题,但是我已经有一段时间了,因为我一直在做任何java。

I am sure this is a basic question, but its been a while since I have been doing any java.

class A
{
 public void myMethod()
 { /* ... */ }
}

class B extends A
{
 public void myMethod()
 { /* Another code */ }
}

class C extends B
{
 I need to call Class A here
 { /* Another code */ }
}


推荐答案

你不这样做:它违反了封装。

You don't: it violates encapsulation.

可以这样说,不,我不想要我自己的行为 - 我想要我父母的行为,因为它是假定的只有当它正确维护你自己的状态时你才会这样做。

It's fine to say, "No, I don't want my own behaviour - I want my parent's behaviour" because it's assumed that you'll only do so when it maintains your own state correctly.

然而,你不能绕过父母的行为 - 这会阻止它强制执行自己的一致性。如果父类想要允许你直接调用祖父表法,它可以通过一个单独的方法公开...但这取决于父类。

However, you can't bypass your parent's behaviour - that would stop it from enforcing its own consistency. If the parent class wants to allow you to call the grandparent method directly, it can expose that via a separate method... but that's up to the parent class.

这篇关于Java:你如何访问两个级别的父类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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