Topics Index

Overriding methods for enum constants - Java Example Program

Overriding methods for enum constants
enum Bats
        public void info()      // LINE A
            System.out.println( "Preferred by most of the players these days" );
    }, SG;
    public void info()       // LINE B
        System.out.println( "Preferred by some players" );

class EnumDemo2
    Bats[] b = Bats.values();
    for( Bats b1 : b );


Preferred by some players
Preferred by most of the players these days
Preferred by some players


In this example, the implementation of info() method is different for ADIDAS as we have overridden info() specifically for ADIDAS. So, for ADIDAS, overridden info() gets executed (LINE A). For HERO and SG, default info() gets executed (LINE B).

  • In the above program, try to define info() behavior specific to other enum constants as well and observe the change in the output.
  • Consider the program from enum vs. switch section. Try to use fully qualified names for switch case labels and see what happens i.e, Move.LEFT, Move.RIGHT etc.
  • We can have main() inside an enum in Java. Declare an enum named Bats with some enum constants and define main() inside it and then try to run the program using enum name.

© meritcampus 2019

All Rights Reserved.

Open In App