Home > Java > javaTutorial > The difference between abstract classes and interfaces in Java

The difference between abstract classes and interfaces in Java

WBOY
Release: 2023-09-16 11:49:02
forward
850 people have browsed it

The difference between abstract classes and interfaces in Java

In Java, abstraction is achieved through abstract classes and interfaces. Both contain abstract methods that subclasses or implementing classes must implement. Following are the important differences between abstract class and interface.

thead>7

Abstract class and interface example

JavaTester.java

public class JavaTester {
   public static void main(String args[]) {
      Animal tiger = new Tiger();
      tiger.eat();
      Cat lion = new Lion();
      lion.eat();
   }
}
interface Animal {
   public void eat();
}
class Tiger implements Animal {
   public void eat(){
      System.out.println("Tiger eats");
   }
}
abstract class Cat {
   abstract public void eat();
}
class Lion extends Cat{
   public void eat(){
      System.out.println("Lion eats");
   }
}
Copy after login

Output

Tiger eats
Lion eats
Copy after login
Sr. No.

Key

Abstract class

Interface

1

Supported methods

Abstract classes can have both abstract methods and concrete methods.

Interfaces can only have abstract methods. Starting from Java 8, it can have default and static methods.

2

Multiple inheritance

Multiple inheritance is not

Interface supports multiple inheritance.

3

Supported variables

Supports final, non- Final, static and non-static variables.

Only static and final variables are allowed.

4

Implementation

Abstract classes can implement interfaces.

The interface does not need to implement the interface, or it can extend the interface.

5

Keyword

Use abstract keyword declaration abstract class.

The interface is declared using the interface keyword.

6

Inheritance

Abstract classes can inherit from another Classes use the extends keyword and implement interfaces.

Interfaces can only inherit interfaces.

Inheritance

Abstract classes can use the extends key Word inheritance.

Interfaces can only be implemented using the implements keyword.

8

Access

Abstract classes can have any type members, such as private and public.

Interfaces can only have public members.

The above is the detailed content of The difference between abstract classes and interfaces in Java. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template