java 如何将一个类的对象传递给另一个类的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7912843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can pass an object of a class to another class's method?
提问by IronBlossom
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
. Can Java help me to do that?
我需要将一个类的对象传递给 classProject
的方法Developer
。Java 可以帮助我做到这一点吗?
回答by bharath
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
}
}
回答by Joachim Sauer
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
}
}
回答by Daniel Teichman
If the class Developer
contains a method that takes an argument of type Project
or any type that Project
inherits from, including Object
, then you can pass an object of type Project
to a method within Developer
如果该类Developer
包含一个方法,该方法采用类型Project
或任何Project
继承自的类型的参数,包括Object
,那么您可以将类型的对象传递Project
给内部的方法Developer
回答by Nicola Musatti
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);
}
}