James Frost
0
Q:

what is method overloading and method overriding in Java?

Method overloading is providing two separate methods in a class with the same name but different arguments, while the method return type may or may not be different, which allows us to reuse the same method name.

Method overriding means defining a method in a child class that is already defined in the parent class with the same method signature, same name, arguments, and return type
3
// Base Class 
class Parent { 
    void show(){ 
        System.out.println("Parent's show()"); 
    } 
} 
// Inherited Class 
class Child extends Parent { 
    // This method overrides show() of Parent Class
    @Override
    void show(){ 
        System.out.println("Child's show()"); 
    } 
}
// Main class 
class Main { 
    public static void main(String[] args){ 
        Parent obj = new Child(); 
		// Calling Child Class Method
        obj.show(); 
    } 
}
1
class Calculate
{
  void sum (int a, int b)
  {
    System.out.println("sum is"+(a+b)) ;
  }
  void sum (float a, float b)
  {
    System.out.println("sum is"+(a+b));
  }
  Public static void main (String[] args)
  {
    Calculate  cal = new Calculate();
    cal.sum (8,5);      //sum(int a, int b) is method is called.
    cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
  }
}
0
// Overloading by Changin the number of Arguments
class MethodOverloading {
    private static void display(int a){
        System.out.println("Arguments: " + a);
    }

    private static void display(int a, int b){
        System.out.println("Arguments: " + a + " and " + b);
    }

    public static void main(String[] args) {
        display(1);
        display(1, 4);
    }
}
0
public static void main(String[] args) {
  int menuOption;
  int foodItem = 0;
  input = new Scanner(System.in);
  double runningTotal=0;
  do{
    menu();
    menuOption = input.nextInt();
    switch(menuOption){
      case 1:
        foodItem = 1;
        runningTotal += itemPrice(foodItem);
        break;
      case 2:
        foodItem = 2;
        runningTotal += itemPrice(foodItem);
        break;
      case 3:
        foodItem = 3;
        runningTotal += itemPrice(foodItem);
        break;
      case 4:
        done(runningTotal);
        break;
      default:
        System.out.println("Invalid option.");
    }
  } while(ordering);
  System.out.println("Total amount: " + runningTotal);
}
-1

New to Communities?

Join the community