user1355347
user1355347

Reputation:

calling methods without having reference

if i want to call multiple methods of a one class from another class can i call them by using only 'new classname()' without catching it in class reference?

public class Example {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new pqr().a=5;
        new pqr().b=10;
        new pqr().display();
    }
}
class pqr
{
        int a,b;

        public void display()
        {
                System.out.println(a+" "+b);
        }

}

Upvotes: 0

Views: 92

Answers (4)

Robert Balent
Robert Balent

Reputation: 1462

The builder pattern is one possibility. The another one is to have static properties so all object will share it's values.

static int a,b;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503140

if i want to call multiple methods of a one class from another class can i call them by using only 'new classname()' without catching it in class reference?

It's not clear what you mean by "catching it" but you are using a reference... you're just not assigning it to a variable.

In your example, you're creating three different objects - the calculation on your final line just prints 0, because you've only set a and b in other objects. If you want to use a single object for multiple operations, you'll either need to store the reference in a variable, or those operations will have to return "this", allowing you to chain method calls together:

class Sample {
    private int a,b;

    public void display() {

        System.out.println(a+" "+b);
    }    

    public Sample setA(int a) {
        this.a = a;
        return this;
    }

    public Sample setB(int b) {
        this.b = b;
        return this;
    }
}

...

new Sample().setA(5).setB(10).display();

This sort of chaining for setters is common in the builder pattern.

Upvotes: 3

Paul Vargas
Paul Vargas

Reputation: 42060

You can use the Builder pattern if you want something like that:

NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
    calories(100).sodium(35).carbohydrate(27).build(); 

Upvotes: 0

Dheeraj Joshi
Dheeraj Joshi

Reputation: 3147

This creates three new objects. Not just one.

new pqr().a=5;
new pqr().b=10;
new pqr().display();

One object with a = 5 and another with b = 10.

Remember you are not working with one object.

Whenever you use new keyword. JVM creates a new object.

Upvotes: 5

Related Questions