abstract method in java
A method without a body (no implementation) is known as an abstract method. A method must always be declared in an abstract class, or in other words, you can say that if a class has an abstract method, it should be declared abstract as well. In the last tutorial we discussed the Abstract class, if you have not yet checked it out read it here: Abstract class in Java, before reading this guide.
This is how an abstract method looks in java:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
What is abstract in Java with example?
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message.
Why do we require abstract method in Java?
By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.
example abstract method:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
II Example abstract method:
abstract class Sum{
/* These two are abstract methods, the child class
* must implement these methods
*/
public abstract int sumOfTwo(int n1, int n2);
public abstract int sumOfThree(int n1, int n2, int n3);
//Regular method
public void disp(){
System.out.println("Method of class Sum");
}
}
//Regular class extends abstract class
class Demo extends Sum{
/* If I don't provide the implementation of these two methods, the
* program will throw compilation error.
*/
public int sumOfTwo(int num1, int num2){
return num1+num2;
}
public int sumOfThree(int num1, int num2, int num3){
return num1+num2+num3;
}
public static void main(String args[]){
Sum obj = new Demo();
System.out.println(obj.sumOfTwo(3, 7));
System.out.println(obj.sumOfThree(4, 3, 19));
obj.disp();
}
}
No comments:
Post a Comment