[英]How can pass an object of a class to another class's method?
How can I pass an object of a class to another class's method without interface or inheritance? 如何在没有接口或继承的情况下将类的对象传递给另一个类的方法?
I need to pass an object of a class called Project
to a method of class Developer
. 我需要将一个名为
Project
的类的对象传递给类Developer
的方法。 Can Java help me to do that? Java能帮我做到吗?
Look on this sample code, 看看这个示例代码,
public class Project {
public Project() {
Developer developer = new Developer();
developer.developerMethod(this);
}
}
public class Developer {
public void developerMethod(Project project) {
// do something
}
}
Yes, you can pass references to any reference type, no matter if it's a class, an interface, an array type, an enum, an annotation or if it's abstract
, final
or even strictfp
: 是的,您可以将引用传递给任何引用类型,无论它是类,接口,数组类型,枚举,注释还是
abstract
, final
甚至strictfp
:
public class Project {
}
public class Developer {
public void myMethod(Project foo) {
// do something with foo
}
}
如果类Developer
包含一个方法,该方法接受类型为Project
的参数或Project
继承的任何类型,包括Object
,那么您可以将Project
类型的对象传递给Developer
的方法
If you can choose the type of your method's parameter, it's quite simple: 如果您可以选择方法参数的类型,那很简单:
class Project {
}
class Developer {
public void complete(Project p) {
}
}
class SoftwareHouse {
public void perform() {
Developer d = new Developer();
Project p = new Project();
d.complete(p);
}
}
If the type of the argument is fixed and it isn't an interface or a super-class of Project
you need to write an adapter class: 如果参数的类型是固定的并且它不是
Project
的接口或超类,则需要编写适配器类:
interface Assignment {
}
class Developer2 {
public develop(Assignment a) {
}
}
class ProjectAssignment implements Assignment {
private Project p;
public ProjectAssignment(Project p) {
this.p = p;
}
}
class SoftwareHouse2 {
public void perform() {
Developer2 d2 = new Developer2();
Project p2 = new Project();
Assignment a = new ProjectAssignment(p);
d2.develop(a);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.