IronBlossom
IronBlossom

Reputation: 3917

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. Can Java help me to do that?

Upvotes: 3

Views: 14092

Answers (4)

Nicola Musatti
Nicola Musatti

Reputation: 18218

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:

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);
    }
}

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308031

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:

public class Project {
}

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

Upvotes: 1

bharath
bharath

Reputation: 14453

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
}
}

Upvotes: 4

Daniel Teichman
Daniel Teichman

Reputation: 610

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

Upvotes: 0

Related Questions