Saturday, 9 July 2022

Can enum implement an interface in Java?

Enum can implement an interface in Java (Enum can have abstract methods too).

 


Example

enum StringConverters implements Converter<String> {
		LOWER {

			@Override
			public String convert(String str) {
				return str.toLowerCase();
			}

		}
}

 

Find the below working application.

 

EnumImplementInterface.java

package com.sample.app;

public class EnumImplementInterface {

	interface Converter<T> {
		T convert(T data);
	}

	public static enum StringConverters implements Converter<String> {
		LOWER {

			@Override
			public String convert(String str) {
				return str.toLowerCase();
			}

		},
		UPPER {

			@Override
			public String convert(String str) {
				return str.toUpperCase();
			}

		},
		CAMELCASE {

			@Override
			public String convert(String str) {
				return toCamelCase(str);
			}

		};

		private static String toCamelCase(final String str) {
			if (str == null || str.isEmpty())
				return null;

			final StringBuilder builder = new StringBuilder();

			for (final String word : str.split(" ")) {
				if (!word.isEmpty()) {
					builder.append(Character.toUpperCase(word.charAt(0)));
					builder.append(word.substring(1).toLowerCase());
				}
				if (!(builder.length() == str.length()))
					builder.append(" ");
			}

			return builder.toString();
		}
	}

	public static void main(String[] args) {
		String str = "Hi Krishna, how are you";

		System.out.println(StringConverters.LOWER.convert(str));
		System.out.println(StringConverters.UPPER.convert(str));
		System.out.println(StringConverters.CAMELCASE.convert(str));
	}

}

Output

hi krishna, how are you
HI KRISHNA, HOW ARE YOU
Hi Krishna, How Are You



 

 

  

You may like

Interview Questions

How to read the file content using an iterator in Java?

Implement a Closeable iterator in Java

Quick guide to generate random data in Java

What are the different cache eviction strategies?


How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

No comments:

Post a Comment