gpt4 book ai didi

java - 有一个函数依赖于 Java 中未指定的类

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:41 24 4
gpt4 key购买 nike

如何在 Java 中实现以下伪代码:

  class A extends B{
int var[];
void someFn(var, WANT TO INPUT EITHER a C1 or C2 CLASS HERE){
//initialize var;
// Call fn(var,C1 or C2)

public static void main(String[] arguments){
///main stuff
}

}

class B{
void fn(int var[], C1 c1){return foo;}
void fn(int var[], C2 c2){return other foo;}
}
class C1{stuff here}
class C2{other stuff here}

我试过了

  class A extends B{
int var[];
public static <C> void someFn(var, C Cclass){
//initialize var;
// Call fn(var, C1 or C2)

但这并没有奏效。我还是 Java 的新手。我宁愿不重载 someFn

最佳答案

现在这只是伪代码的实现

package com.so;

public class A extends B{
int var[];
void someFn(int[] var, Object object){
this.var = var;
if (object instanceof C1){
fn(var,(C1) object);
}
else if (object instanceof C2){
fn(var,(C2) object);
}


}

public static void main(String[] arguments){
A a = new A();
int[] i = {1,2};
C1 c1 = new C1();
a.someFn(i, c1);
}

}

class B{
void fn(int var[], C1 c1){
System.out.println("C1 func");
/*Void can not return even foo*/
}
void fn(int var[], C2 c2){
System.out.println("C2 func");
/*Void can not return even other foo either*/
}
}

class C1{}
class C2{}

使用泛型

public class A<T> extends B<T>{
int var[];
void someFn(int[] var, T t){
this.var = var;
fn(var,t);


}

public static void main(String[] arguments){
A<C1> a = new A<C1>();
int[] i = {1,2};
C1 c1 = new C1();
a.someFn(i, c1);

C2 c2 = new C2();
//a.someFn(i, c2); //This will give you complie time error because of typesafety (good thing)

A<C2> a2 = new A<C2>();
a2.someFn(i, c2);
}

}

class B<T>{
void fn(int var[], T c){
System.out.println(c.getClass().getName() +"func");
/*Void can not return even foo*/
}

}

class C1{}
class C2{}

关于java - 有一个函数依赖于 Java 中未指定的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com