Reputation: 4399
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
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
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
Reputation: 22812
You have two ways to do that.
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
}
}
Like that:
class MyClass {
public void myMethod(int a) {
if (a == 1)
// do something
if (a == 2)
// do something else
}
}
Upvotes: 6
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