hattenn
hattenn

Reputation: 4399

Passing an argument to a class in Java

Let's say I have a class and I want one of its methods to behave differently depending on an argument. What I want to do is something like this (I know this doesn't work in Java):

class myClass(int a) {
    public void myMethod() {
        if (a == 1)
            // do something
        if (a == 2)
            // do something else
    }
}

Is there a way to do this?

Upvotes: 2

Views: 915

Answers (4)

yegor256
yegor256

Reputation: 105043

Polymorphism is the way to go. Define your base class first with an abstract method myMethod() and then extend it with two classes providing two different implementations of the method.

Upvotes: 1

M S
M S

Reputation: 4093

You can pass this argument in constructor

class MyClass {
    private int a;
    public MyClass(int a){
        this.a = a;
    }
    public void myMethod() {
        if (a == 1)
            // do something
        if (a == 2)
            // do something else
    }
}

Upvotes: 2

Guillaume
Guillaume

Reputation: 22812

You have two ways to do that.

  • Pass the argument to the class contructor, and keep a local reference to it. You can then use it in all the methods of your class.

Like this:

class MyClass {
    private final int a;

    public MyClass(int a) {
        this.a = a;
    }

    public void myMethod() {
        if (a == 1)
            // do something
        if (a == 2)
            // do something else
    }
}
  • Pass the argument to the method, if you intend to use it only in that method.

Like that:

class MyClass {
    public void myMethod(int a) {
        if (a == 1)
            // do something
        if (a == 2)
            // do something else
    }
}  

Upvotes: 6

JB Nizet
JB Nizet

Reputation: 691635

The argument must be passed to the method, not to the class:

class MyClass { // note that class names should start with an uppercase letter.
    public void myMethod(int a) {
        if (a == 1)
            // do something
        if (a == 2)
            // do something else
    }
}

Read the Java language tutorial.

Upvotes: 4

Related Questions