Java:如何从超类访问子类方法的实现 [英] Java: How to access implementation of a method of Sub class from Super class

查看:269
本文介绍了Java:如何从超类访问子类方法的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经明白了这一点,所以我需要理解这一点,我认为我应该把它放在那里,可能会帮助某人:

I needed to understand this, now that I have figured this out, I thought I should put it out there, might help someone:

如何访问超类内部子类提供的方法的实现?

How to access implementation of a method provided by subclass inside super class?

请考虑您正在某个类中实现方法的情况,该方法最终将被其他类扩展.您的班级需要的信息仅在子类在运行时提供后才可用.您如何使用在运行时可用的方法?

Consider a situation that you are implementing a method in a class that will eventually be extended by other classes. Your class needs information that will only be available after a sub class has provided it at runtime. How do you use a method that will be available at runtime?

推荐答案

请考虑以下内容:

public interface Animal {

    bool isVertebrate();
    bool isDomesticable();  
}

和实现此接口的抽象类:

and an abstract class that implements this interface:

abstract class Cat implements Animal {

public bool isVertebrate() {return true;}

public void dealWithCat(){
if (isDomesticable()){
 ...
   }
}

但是isDomesticable的实现被委派给子类:

But implementation for isDomesticable is delegated to subclass:

public class Tiger extends Cat {

public bool isDomesticable(){
return false;
}

由于Cat是abstract,因此无法实例化.为某些接口方法提供实现是免费的,但不必为每种方法都提供实现.它不提供实现的方法必须由子类提供.并且在运行时,超类中的方法从子类中获取实现.因此,在我们的示例中,isDomesticable()的实现不是由Cat提供的,而是后来由Tiger实现的.

Since Cat is abstract, it can't be instantiated. It is free to provide implementation for some interface methods, but doesn't have to provide it for every method. The methods that it doesn't provide implementation for, must be provided by by subclass. And at run time, methods in super class get implementation from subclass. So in our example, implementation of isDomesticable() is not provided by Cat but it is later implemented by Tiger.

这篇关于Java:如何从超类访问子类方法的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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