// Abstract Class example
abstract class nano{ abstract void Speed(); public void Weight() { System.out.println("250 Kg"); } } class Vehicles extends nano{ @Override void Speed() { System.out.println("90 kmph"); } } class Main{ public static void main(String[] args) { Vehicles vehicles=new Vehicles(); vehicles.Speed(); vehicles.Weight(); } }
Output:
90 kmph
250 Kg
An abstract method is one that is declared with abstract keyword but does not have implementation.
Syntax
abstract void Exam(); // does not have implementation
In Java, an interface is a reference type that details a collection of abstract methods or a contract that a class must adhere to. Without specifying how those methods should be implemented, it lists the methods that a class must offer. In other words, an interface specifies what a class that implements it should do, but not how.
Using interfaces to achieve abstraction, you can distinguish between how a behaviour is defined and how it is actually implemented. You can write more flexible and maintainable code by clearly separating the implementation from the interface (what should be done and how it should be done).
// Java method overridden example
interface Displayable { void display(); } class Test implements Displayable { public void display(){ System.out.println("Hello"); } } class Main{ public static void main(String[] args){ Test test = new Test(); test.display(); } }
Output:
Hello
Difference Between Interface and Abstract class are mention below
S.N | Aspect | Interface | Abstract class |
---|---|---|---|
1. | Methods | Interface can have only abstract methods. | An abstract class can have abstract and non-abstract methods. Java 8 allows for the addition of default and static methods. It can also have private concrete methods as of Java 9. |
2. | Variables | By default, variables declared in a Java interface are final,public and static. | Abstract class can have only Non-final variables. |
3. | Access | The interface's definitions are all assumed to be public by default. | A Java abstract class may have class members such as private, protected, and so on. |
4. | Implementation | Interface use "implements" keyword for implementation | The keyword "extends" can be used to extend an abstract class. |
5. | Inheritance | Interface supports multiple inheritance | Multiple inheritance is not supported by the abstract class. |
6. | Code | Since an interface is abstract, it does not provide any code implementation | An abstract class can provide Default code with optional overrides |
Police Colony
Patna, Bihar
India
Email:
Post your comment