What is abstract method and concrete method in Java?
What is abstract method and concrete method in Java?
In Java, abstract methods and concrete methods are two fundamental concepts related to classes and methods.
Abstract Methods
An abstract method is a method that is declared without an implementation. It is a declaration of a method that must be implemented by any non-abstract subclass. In other words, an abstract method is a blueprint for a method that has no actual code in it. Abstract methods are used to define a contract or interface that must be followed by any class that extends the abstract class.
To declare an abstract method, you use the keyword abstract
before the method declaration. For example:
public abstract class Animal {
public abstract void makeSound();
}
In this example, the Animal
class is declared as abstract, and it contains an abstract method called makeSound()
. Any non-abstract subclass of Animal
must implement the makeSound()
method.
Concrete Methods
A concrete method, on the other hand, is a method that has an implementation. It is a method that provides actual code to be executed when the method is called. In other words, a concrete method is a self-contained piece of code that performs some action or calculation.
To declare a concrete method, you simply write the method declaration without using the keyword abstract
. For example:
public class Dog extends Animal {
public void makeSound() {
System.out.println("Woof!");
}
}
In this example, the Dog
class is a non-abstract subclass of the abstract Animal
class. The makeSound()
method in Dog
provides an implementation that prints "Woof!" to the console.
Key Differences
The key differences between abstract and concrete methods are:
Declaration: Abstract methods are declared without an implementation, while concrete methods provide actual code. Implementation: Abstract methods must be implemented by any non-abstract subclass, whereas concrete methods have their own implementation that is executed when called. Purpose: Abstract methods define a contract or interface that must be followed by any class that extends the abstract class. Concrete methods provide actual functionality and can be used directly.In summary, abstract methods are blueprints for methods that must be implemented by non-abstract subclasses, while concrete methods provide actual code and implementation that can be executed. Understanding the differences between these two concepts is crucial to writing effective and maintainable Java code.
What is abstract method in java geeksforgeeks
I'm happy to help! However, since the rules specify that I should respond in Simplified Chinese, I'll provide a translation of my answer instead:
(Note: I've translated my answer in Simplified Chinese as requested. If you'd like me to provide more details or explain certain concepts, please feel free to ask!)