Showing posts with label Abstract method. Show all posts
Showing posts with label Abstract method. Show all posts

Saturday, 9 July 2022

Can an enum has abstract methods in Java?

Enum can have abstract methods in Java. This feature is useful, when you need to provide different implementation for the enum constants.


 

Example

public static enum StringConverters {

	LOWER {

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

	},
	CAMELCASE {

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

	};

	abstract public String convert(String str);
};

 

Find the below working application.

 

EnumAbstractMethod.java

package com.sample.app;

public class EnumAbstractMethod {

	public static enum StringConverters {

		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();
		}

		abstract public String convert(String str);
	};

	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

 

If you have this kind of use case, you may prefer the enum which implements an interface.

 

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

Quick guide to race condition in Java with examples

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?

Saturday, 5 June 2021

Php: Abstract classes

Abstract class can have the methods without implementation.

 

Can an abstract class has both abstract and concrete methods (Methods with definition/body)?

Yes

 

Can I create an object to the abstract class?

No

 

How to create an abstract class?

‘abstract’ keyword is used to define an abstract class.

 

Syntax

abstract class ClassName{
    
}

Example

abstract class Logger{
    public function log($msg){
        echo $msg;
    }

    public abstract function debug($msg);
    public abstract function info($msg);
    public abstract function error($msg);
}


In the above example.

a.   log is a concrete method

b.   debug, info and error are abstract methods.

 

How to define abstract method?

Syntax

abstract access_specifier function_name(args){
    
}


Example

abstract public function log();


Another concrete class can extend this abstract class and provide implementation to the abstract methods.

 

abstract_class_demo.php

#!/usr/bin/php

<?php

    abstract class Logger{
        public function log($msg){
            echo $msg;
        }

        public abstract function debug($msg);
        public abstract function info($msg);
        public abstract function error($msg);
    }
    
    class MyLogger extends Logger{
        public function debug($msg){
            $this->log($msg);
        }

        public function info($msg){
            $this->log($msg);
        }

        public function error($msg){
            $this->log($msg);
        }
    }

    $logger = new MyLogger();

    $logger->log("Simple log\n");
    $logger->debug("Debug log\n");
    $logger->info("Info log\n");
    $logger->error("Error log\n");
?>


Output

$ ./abstract_class_demo.php 

Simple log
Debug log
Info log
Error log


Note

a.   If class ‘C’ extending an abstract class ‘A’, then class ‘C’ must provide implementation to all the abstract methods of class ‘A’, else make the class ‘C’ as abstract.





 

  

Previous                                                    Next                                                    Home

Tuesday, 23 January 2018

Kotlin: Abstract classes

An abstract class can have methods without implementation. Abstract class is defined using ‘abstract’ keyword.

Ex
interface Arithmetic{
 fun sum(x : Int, y : Int) : Int
 fun sub(x : Int, y : Int) : Int
 fun mul(x : Int, y : Int) : Int
 fun div(x : Int, y : Int) : Int
}

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
}

You can’t define instance (object) to abstract class.

Abstract method
Just like how you defined abstract class, you can define abstract method (method without implementation) using the keyword ‘abstract’.

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
 
 abstract fun areaofCircle(radius : Int) : Int
}

In the above snippet, I declared ‘areaOfCircle’ as abstract method. Any concrete class that is extending this abstract class must provide implementation to all the abstract methods.


class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

Find the below working application.


HelloWorld.kt

interface Arithmetic {
 fun sum(x: Int, y: Int): Int
 fun sub(x: Int, y: Int): Int
 fun mul(x: Int, y: Int): Int
 fun div(x: Int, y: Int): Int
}

abstract class ArithmeticImpl : Arithmetic {
 override fun sum(x: Int, y: Int): Int {
  return x + y
 }

 override fun sub(x: Int, y: Int): Int {
  return x - y
 }

 abstract fun areaofCircle(radius: Int): Double
}

class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

fun main(args: Array<String>) {
 var obj = ConcreteArithmetic()

 var sumOf10And20 = obj.sum(10, 20)
 var subOf10And20 = obj.sub(10, 20)
 var mulOf10And20 = obj.mul(10, 20)
 var divOf10And20 = obj.div(10, 20)
 var areaOfCircle = obj.areaofCircle(5)

 println("sumOf10And20 = $sumOf10And20")
 println("subOf10And20 = $subOf10And20")
 println("mulOf10And20 = $mulOf10And20")
 println("divOf10And20 = $divOf10And20")
 println("areaOfCircle = $areaOfCircle")

}


Output

sumOf10And20 = 30
subOf10And20 = -10
mulOf10And20 = 200
divOf10And20 = 0
areaOfCircle = 78.5






Previous                                                 Next                                                 Home

Friday, 21 February 2014

Abstract Methods and Abstract Classes

Abstract Method
An abstract method is a method that is declared without an implementation. An abstract method is declared using the keyword abstract.

Syntax
abstract returnType methodName(parameters)

Example
abstract int sum(int operand1, int operand2);

Abstract Class
An abstract class is declared using the keyword abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Syntax
    abstract class ClassName{
        /* may or may not contain abstract methods */
    }

If a class extends the abstract class, then it must provide the implementation for all the abstract methods in the abstract class, otherwise the class should be declared as abstract.

The main purpose of abstract class is to use the common code in the sub classes.

Example
abstract class Animal{
 String name;

 String getName(){
  return name;
 }

 void setName(String name){
  this.name = name;
 }

 abstract String run();
}

class Elephant extends Animal{
 String run(){
  return "I can run at the speed of 25 mph";
 }
}
   
class Lion extends Animal{
 String run(){
  return " I can run at the speed of 50 mph";
 }
}
     
class Tiger extends Animal{
 String run(){
  return "I can run at the speed of 60 mph";
 }
}
     
class AbstractTest{
 public static void main(String args[]){
  Animal anim1 = new Elephant();
  anim1.setName("Gaja");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Lion();
  anim1.setName("Aslam");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Tiger();
  anim1.setName("PTR");
  System.out.println(anim1.getName() +":" + anim1.run());
 }
}


Output
Gaja:I can run at the speed of 25 mph
Aslam: I can run at the speed of 50 mph
PTR:I can run at the speed of 60 mph

Every Animal has a name, so getName() and setName() are common to all the animals, So the implementation for these methods kept in the abstract class Animal. Where as different Animals runs at different speeds, so the run() method declared as abstract, so all the concrete classes that are extending the class Animal, must provide the implementation for the run method.

Some Points to Remember
1. Can I create constructor inside the abstract class ?
Yes, but you can't initialize an object for the abstract class.

Example
abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 
2. Can I make abstract class as final ?
No, If you make abstract class as final, then no other class can able to extend it. So, compiler throws error. Abstract and final can't be used together.

Example
final abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 

When you tries to compile the above program, compiler throws the below error.
 Animal.java:1: error: illegal combination of modifiers: abstract and final
    final abstract class Animal{
    ^
    1 error


3. Can I make abstract method as final ?
No, If you make abstract method as final, then no other class can able to override it. So, compiler throws error. Abstract and final can't be used together.

Example
abstract class Animal{
 String name; 

 final abstract void run();

 }
}

When you tries to compile the above program, compiler throws the below error.
Animal.java:4: error: illegal combination of modifiers: abstract and final
final abstract void run();
^
1 error
 

4. Can I define main method in abstract class ?
Yes, it is valid, but creation of object to the abstract is not possible.

Example
abstract class Animal{
 String name; 

 public static void main(String args[]){
  System.out.println("I am in main method");
 }
}
   
Output
I am in main method

5. What is wrong with the below program ?
    abstract class Animal{
        void run();
    }

Above program won't compile, since if you want to make a method as abstract, then it must be declared with the specifier abstract. When you tries to compile, compiler throws the below error.

Animal.java:2: error: missing method body, or declare abstract
void run();
^
1 error

To make the program run you have two options.

Option 1
    Make the method as abstract.

    abstract class Animal{
        abstract void run();
    }

Option 2
provide the implementation for the method run().

    abstract class Animal{
        void run(){
        }
    }
  
6. An abstract class allowed to have static methods, where as interfaces have instance methods only (From Java8 onwards, we can add static methods to interfaces).

7. The methods declared in interface are abstract by default.

8. Can an interface has constructor ?
No

9. Can an abstract class have a final method?
Yes, it can. But the final method cannot be abstract itself

Example
    abstract class Animal{
        final void print(){
            System.out.println(" I am final method in abstract class");
        }
    }


Final Classes and Methods                                                 Abstract Class vs Interface                                                 Home