本文介绍了如何覆盖父类中的方法并在子类中执行它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ì'm 试图了解覆盖和超类,我想做的是在调用父类中的方法时覆盖它.而是执行子类中的那个.我该怎么做?这是一个java控制的plc.

ì'm trying to learn about override and super class, what i would like to do is override the method in the parent when it is called. And instead execute the one in the child class. How would i do this? it is for a java controlled plc.

public class BIhcs_IO extends BComponent implements Runnable {

//Example of a created property for a PLC IO
public static final Property bool_1 = newProperty(Flags.EXECUTE_ON_CHANGE | Flags.OPERATOR | Flags.SUMMARY, ((BBoolean)((BValue)BBoolean.TYPE.getInstance())).getBoolean(), BFacets.tryMake(null));
public boolean getBool_1() { return getBoolean(bool_1); }
public void setBool_1(boolean v) { setBoolean(bool_1, v, null); }

public static final Action execute = newAction(Flags.ASYNC, null);
public void execute() { invoke(execute, null, null); }


@Override
public Type getType() { return TYPE; }
public static final Type TYPE = Sys.loadType(BIhcs_IO.class);


public BComponent getComponent() {
    return this;
}

public void started() throws Exception {
}

//When the Property bool_1 changes it wil execute the doExecute() method below
public void changed(final Property prop, final Context cx) {
    super.changed(prop, cx);
    if (!this.isRunning()) {
        return;
    }
    if (Flags.isExecuteOnChange((BComplex) this, (Slot) prop)) {
        this.execute();
    }
}

public void run() {
    System.out.println("Source BProgram did not override run(). Exiting thread.");
}

//This is called when a property changes value. When this is called, instead of executing this i want to execute the code in BIhcsMain()
public void doExecute() throws Exception {
   setDebug_1("called parent")
}

public void stopped() throws Exception {
    }
}   

下面是子类.所以当父类中的 doExecute() 被调用时,我想覆盖它并在子类中执行它.所以唯一的输出将是称为孩子"

Below is the child class. So when the doExecute() in the parent is called i want to override it and execute it in the child class. so the only output would be "called child"

public class BIhcsMain extends BIhcs_IO {

@Override
public void doExecute(){
setDebug_2("called child");
    }
}

推荐答案

只要方法签名相同

  1. 同名

以相同的顺序接受相同类型的参数(不是参数名称,只是检查类型和顺序)

accepts same type of parameters in the same order (not name of parameters just types and order is checked)

它将被覆盖.正如您输入的那样,它是正确的,将被覆盖.

It will be overriden. As you have typed it is correct and will be overriden.

如果你做

parentClass parent = new childClass()
parent.doExecute() -> the children method will get executed

  • 请记住,方法返回类型不是方法签名的一部分,因此不会被检查.
  • 这篇关于如何覆盖父类中的方法并在子类中执行它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:39