英文:
Java, static and instance methods with same name
问题
My code will start on Line 445
I am currently working on my college assignment, and as part of the requirements, I must create both static and instance methods with the same name, such as "isPrime()". What should I do?
英文:
My code will start on of following Line445
I currently working on my college assignment and as part of requirement,
I must make some of static and instance methods with having same name.
Such as I require to make both instance/static methods named isPrime()
What should I do?
Edit/Add/Screenshot
It worked!
// class
public class MyInteger {
// Field
private int num;
public MyInteger(int someNum){
num = someNum;
}
//Method
private void setNum(int setNum){
num = setNum;
}
public int getNum(int getNum){
return getNum;
}
public int toInteger(){
num = Integer.valueOf(num);
return num;
}
public boolean isPrime(){
if (num < 2){
//prime number must be larger than 1
return false;
}
for (int i = 2; i < num; i++){
//if any number result 0 reminder until self, it is not prime
if(num % i == 0){
return false;
}
}
return true;
}
}
答案1
得分: 2
您可以使用相同的方法名称,只要它们的参数(括号内的输入)不同。例如,您可以有:
public boolean isPrime() { ... }
public static boolean isPrime(int num) { ... }
但不可以有:
public boolean isPrime() { ... }
public static boolean isPrime() { ... }
英文:
You can make two methods with the same name so long as their parameters (the input from the brackets) are different. So for example you could have
public boolean isPrime() { ... }
public static boolean isPrime(int num) { ... }
but not
public boolean isPrime() { ... }
public static boolean isPrime() { ... }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论