简体   繁体   中英

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?

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

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM