3 回答

TA贡献1725条经验 获得超8个赞
Java 中的整数是原始类型,按值传递。所以你并没有真正将“路径”传递给整数,而是传递实际值。另一方面,对象是通过引用传递的。
您的伪代码只需稍作修改即可在 Java 中运行。该代码假定所有类都在同一个包中,否则您需要将所有内容公开(或其他访问修饰符,具体取决于用例)。
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
此代码首先定义了 MainClass 类,其中包含您的方法hey。我将方法设为静态,以便能够将其称为MainClass.hey(). 如果它不是静态的,则需要在 Declare 类中实例化 MainClass 对象,然后调用该对象的方法。例如:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...

TA贡献1854条经验 获得超8个赞
Java(从 Java 8 开始)包含函数式编程的元素,它允许与您正在寻找的东西类似的东西。您的hey方法可能如下所示:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
此方法声明了一个参数,该参数可以是“将返回整数的方法调用”。
您可以调用此方法并将其传递给所谓的 lambda 表达式,如下所示:
hey(() -> myObject.getInt());
或者,在某些情况下,您可以使用所谓的方法引用,例如:
Hey(myObject::getInt)
在这种情况下,两者都意味着“调用 hey 方法,当它需要一个整数时,调用 getInt 来检索它”。lambda 表达式还允许您直接引用字段,但公开字段被认为是一种不好的做法。

TA贡献1785条经验 获得超4个赞
如果我正确理解了您的问题,您需要使用继承来实现您正在寻找的东西。
让我们从创建层次结构开始:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
@override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
@override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
现在,您的方法 Signature 可以接受 SuperInteger 类型的参数,并且在调用该方法时,您可以传递 SubIntA/SuperInteger/SubIntB,因为 Java 为您隐式向上转换。
所以:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
可以从 main 调用:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
获得如下输出:
A Value is :3
B Value is :3
The Value is :3
添加回答
举报