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