Product Method Overloading

谁说胖子不能爱 提交于 2019-12-20 04:53:45

问题


so I was working on this problem on CodeHS, then I was stuck for so long so decided to ask here.

The exercise is to overload the product method to allow for multiplying together other types of values:

  1. two doubles
  2. an int and a double
  3. a double and an int
  4. three ints
  5. three doubles

    public class Product extends ConsoleProgram
    {
        public void run()
        {
            int intValue = 5;
            double doubleValue = 2.5;
    
            int product1 = product(intValue, intValue);
            System.out.println(product1);
    
            // Use method overloading to define methods 
            // for each of the following method calls
    
            double product2 = product(doubleValue, doubleValue);
            System.out.println(product2);
    
            int product3 = product(intValue, intValue, intValue);
            System.out.println(product3);
    
            double product4 = product(intValue, doubleValue);
            System.out.println(product4);
    
            double product5 = product(doubleValue, intValue);
            System.out.println(product5);
    
            double product6 = product(doubleValue, doubleValue, doubleValue);
            System.out.println(product6);
        }
    
        public int product(int one, int two)
        {
            return one * two;
        }
    }
    

Thank you


回答1:


be aware that overloading means, the name of the method and the return type remains the same as the original/ initial method.

then you need to define/ implement those methods>

2 doubles would be:

public int product(double one, double two)
{
    return (int)(one * two);
}

an int and a double would be

public int product(int one, double two)
{
    return (int)(one * two);
}

etc




回答2:


Method overloading means you can create methods with same method name by changing those methods parameters (parameter count,parameter type and parameter Patterns). Combination of method name and parameters also called as method signature

Following is an example for method overloading.

public void int myMethod(){} 

public void int myMethod(int a){} 

public void String myMethod(String a){} 

public void double myMethod(int a , String a){} 

public void int myMethod(String a,int a){} 

Note that you can't overload methods by changing return type



来源:https://stackoverflow.com/questions/47321881/product-method-overloading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!