我是Java的新手,我正在编写一个程序,该程序使用同一父方法具有两个子类,我想以一种方法来跟踪哪个调用该方法。
示例:
public class Parent(){
public static int ChildOneUses, ChildTwoUses;
public void Example(){
/* code */
if(/*ChildOne called the method*/)
ChildOneUses++;
else if(/*ChildTwo called the method*/)
ChildTwoUses++;
}
}
public class ChildOne extends Parent(){
/* code */
}
public class ChildTwo extends Parent(){
/* code */
}
public static void main(String[] args){
ChildOne ChildOne = new ChildOne();
ChildTwo ChildTwo = new ChildTwo();
ChildOne.Example();
ChildTwo.Example();
ChildTwo.Example();
}
/* If this code were to run, ChildOneUses would equal 1 and ChildTwoUses would equal 2 */
我不确定这个问题甚至还有一个答案,而只是将父级方法移至每个子类以自己跟踪。
您可以在父类中设置儿童术。
public class Parent(){
public static int childOneUses, childTwoUses;
public static int childType;
public Parent(int childType) {
this.childType = childType;
}
public void example(){
if(childType == 1) {
childOneUses++;
}
else if(childType == 2) {
childTwoUses++;
}
}
}
public class ChildOne extends Parent(){
public ChildOne() {
super(1);
}
}
public class ChildTwo extends Parent(){
public ChildTwo() {
super(2);
}
}
public static void main(String[] args){
ChildOne childOne = new ChildOne();
ChildTwo childTwo = new ChildTwo();
childOne.example();
childTwo.example();
childTwo.example();
}
u可以在子类中制作的方法,该方法显示班级的名称,或者您可以在父级中进行此方法,让其他孩子赚取该方法要跟踪你,让ocject调用此方法 nameofobject.getClass()。getName()
例如,如果您服用字符串S并写 s.getClass()。getName()输出IS Java.lang.String 现在您可以使用此输出播放,并且只需在您想要的情况下使用最后一个字,并且您获得了类名称