user5657755
user5657755

Reputation:

Passing an object of the current class to another class

Okay, I'm unsure whether this is a stupid question or not.

I'm trying to ensure that I use as little static methods in my code as possible as at the moment its a complete mess, I want to create as best an OO approach as possible.

Is it considered bad practice to create an object of the current class you're in and then to pass the value?

is it even possible?

for example..

    public class Details{
        int age;
        String name;
        String countryOfBirth;

        public Details(int age, String name, String countryOfBith){
            this.age = age;
            this.name = name
            this.countryOfBirth = countryOfBirth;
        }

        // how would I use these values to then pass them to another class as an object?

        Candidate can = new Candidate(Details 

}

The reason I need to know this is because I wish to use methods within this specific class corresponding to the values in the class. I'm using semaphores if you need to know that

For example, I want to pass the object but I only want one specific value..

Upvotes: 1

Views: 628

Answers (1)

Igwe Kalu
Igwe Kalu

Reputation: 14868

It's OK to do so, and most commonly in a console application an instance of the class containing the mainmethod is often created in the main method itself and used to do one thing or the other. The following demonstrates the point:

public class Hello {
    public static void main (String args[]) {
        Hello hello = new Hello();
        hello.say();
    }

    public void say() {
        System.out.println ("Hello World!");
    }
}

With the the example you provided in context, it's fine to write

Candidate can = new Candidate(this);

Upvotes: 1

Related Questions