Java强制字段继承 [英] Java force fields inheritance

查看:147
本文介绍了Java强制字段继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于Java继承的帖子(我已经读过它了),但它们都代表它是怎么回事,我需要知识如何改变它。所以,我们有2个类:

I know there have been lots of thread about Java inheritance (and i already read it), but they all stand for "how it is", and I need knowledge "how to change it". So, we have 2 classes:

class t1{
 public int a=5;

 public void get(){
    System.out.println(a);
 }
}

class t2 extends t1{
 public int a = 1;
}

现在:

 t2 z = new t2();
 z.get();

我们得到 5

它只是一个例子,但我想做的是在超类中使用一些常用方法,这些方法将使用继承类中的字段,例如。用户消息

Of cource it is just example, but what i want to do is make some common methods in superclass which will use field from inherited class, ex. user messages

有没有办法做到这一点?如果没有那么为什么我会使用超类,我可以使用其他任何东西吗?

Is there any way to do this? If not then why i would use superclasses, can i use anything else?

提前致谢

推荐答案

是的,有办法解决这个问题。您可以应用称为模板方法的模式。下面是一个示例

Yes, there is a way do to this. You can apply pattern which called "Template method". Here is an example

class Base {

     void someMethod() {
         int value = getValue();

         // calculate something
     }

     protected abstract int getValue();
}

class Derived extends Base {

    int getValue() {
         return 5;
    }
}

其中 getValue()是你的模板方法,你可以在你继承的类实现中插入任何逻辑。

Where getValue() is your template method and you can insert any logic in your inherited classes implementations.

这篇关于Java强制字段继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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