"What is Concrete Method in Java with Example"
In the vast landscape of Java programming, the concept of method overloading and overriding often leads to confusion. One such concept is the concrete method in Java. But what exactly is it, and how does it differ from abstract methods? Let's delve into the world of concrete methods in Java, complete with examples to illustrate their usage.
Understanding Concrete Methods in Java
A concrete method in Java is a method that has a body and performs a specific task. It's the opposite of an abstract method, which is a method signature declared in an interface or an abstract class but without a method body. Concrete methods are also known as non-abstract methods.
Concrete Methods vs Abstract Methods
Here's a simple way to understand the difference:
- Concrete Method: A method with a body that performs a task. It's not declared abstract.
- Abstract Method: A method declared in an interface or an abstract class without a body. It's declared with the 'abstract' keyword.
Concrete Methods in Java with Examples
Let's look at some examples to understand concrete methods better.
Example 1: A Simple Concrete Method
Here's a simple Java class with a concrete method:
In this example, `sayHello` is a concrete method because it has a body that performs a task - printing "Hello, World!".
Example 2: Concrete Methods in Inheritance
Concrete methods play a crucial role in inheritance. They can be overridden in subclasses, providing a way to achieve runtime polymorphism.
Consider the following example:
In this example, `makeSound` is a concrete method in the `Animal` class. It's overridden in the `Dog` class, providing a specific implementation for dogs.
Example 3: Concrete Methods in Interfaces
From Java 8 onwards, interfaces can have default methods, which are essentially concrete methods. Here's an example:
```java interface Flyable { default void fly() { System.out.println("Flying high"); } } class Bird implements Flyable { // Bird class can use the default fly method from the Flyable interface } ```In this example, `fly` is a concrete method in the `Flyable` interface. It's marked as 'default', indicating that it has a default implementation that can be used by any class implementing the interface.
When to Use Concrete Methods
Concrete methods are used whenever you want to provide a specific implementation for a method. They are the building blocks of any Java application, allowing you to define the behavior of your classes and interfaces.
In conclusion, understanding concrete methods is crucial for any Java developer. They are the foundation of object-oriented programming in Java, enabling polymorphism, inheritance, and interface implementation. So, the next time you write a method in Java, remember that it's a concrete method unless you explicitly declare it as abstract.