Sara
0
Q:

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
class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal a = new Animal();   // Animal reference and object
      Animal b = new Dog();   // Animal reference but Dog object

      a.move();   // runs the method in Animal class
      b.move();   // runs the method in Dog class
   }
}
1
// 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
// 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