An abstract class is a class that is declared with the abstract
keyword, which means that it cannot be instantiated directly. An abstract class is designed to be extended by other classes, and it provides a base set of methods or functionality that derived classes can implement or override. An abstract class can have both abstract and non-abstract methods.
An abstract method is a method that is declared with the abstract
keyword, but does not have an implementation. It only has a method signature, which includes the method name, return type, and parameters, but does not have any method body. Abstract methods are declared in abstract classes, and they are meant to be implemented by non-abstract subclasses.
abstract class Base {
public abstract void firstAbsMethod();
public abstract void secondAbsMethod();
}
class Details extends Base {
public void firstAbsMethod() {
System.out.println("I am from firstAbsMethod");
}
public void secondAbsMethod() {
System.out.println("I am from secondAbsMethod");
}
}
public class Main {
public static void main(String[] args) {
Details someObj = new Details();
someObj.firstAbsMethod();
someObj.secondAbsMethod();
}
}
Here is a block-by-block explanation of the code:
abstract class Base {
public abstract void firstAbsMethod();
public abstract void secondAbsMethod();
}
This defines an abstract class Base
that contains two abstract methods named firstAbsMethod
and secondAbsMethod
. These methods have no implementation and are intended to be overridden by subclasses of Base
.
class Details extends Base {
public void firstAbsMethod() {
System.out.println("I am from firstAbsMethod");
}
public void secondAbsMethod() {
System.out.println("I am from secondAbsMethod");
}
}
The Details
class extends the Base
class and provides implementations for the two abstract methods declared in Base
. In other words, Details
is a concrete class that can be instantiated and used. It defines its own behavior for the two abstract methods, providing the necessary implementations.
public class Main {
public static void main(String[] args) {
Details someObj = new Details();
someObj.firstAbsMethod();
someObj.secondAbsMethod();
}
}
Finally, the Main
class contains a main
method that creates an instance of Details
and calls its firstAbsMethod
and secondAbsMethod
methods. The output of running this program will be:
I am from firstAbsMethod
I am from secondAbsMethod
This demonstrates the concept of abstract classes and methods in Java, where a subclass must provide implementations for the abstract methods declared in its superclass, or else be declared abstract itself.
No comments:
Post a Comment