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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:58:45  来源:igfitidea点击:

How can pass an object of a class to another class's method?

java

提问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 Projectto 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, finalor even strictfp:

是的,您可以传递对任何引用类型的引用,无论它是类、接口、数组类型、枚举、注释还是abstractfinal甚至是strictfp

public class Project {
}

public class Developer {
  public void myMethod(Project foo) {
    // do something with foo
  }
}

回答by Daniel Teichman

If the class Developercontains a method that takes an argument of type Projector any type that Projectinherits from, including Object, then you can pass an object of type Projectto 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 Projectyou 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);
    }
}