Java中,具有相同名称的静态方法和实例方法

huangapple go评论58阅读模式
英文:

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!
Java中,具有相同名称的静态方法和实例方法

Edit/Add/Screenshot
Java中,具有相同名称的静态方法和实例方法

 // 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() { ... }

huangapple
  • 本文由 发表于 2020年8月6日 02:33:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63271494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定