Difference between interface and class in Java
This article, explains the difference between an interface and a class in Java.
Class
A class is a user-defined blueprint for creating objects.
- The “class” keyword is used for creating classes.
- A class can be instantiated, which means a class can create objects.
- It does not support multiple inheritances.
- A class can inherit another class.
- It contains constructors.
- It doesn’t contain any abstract methods.
- Methods and variables in a class can be declared using any access modifiers (private, protected, public)
Class implementation in Java
# Example of class in Java
class ClassExample{ private String name; ClassExample(String name){ this.name = name; } public void display(){ System.out.println("My name is "+name); } } public class Main { public static void main(String[] args) { ClassExample obj1 = new ClassExample("Jonny"); obj1.display(); } }
Output
My name is Jonny
Interface
The interface is a blueprint of the class. It defines what a class should do but not how.
- The “interface” keyword is used for creating interfaces in Java.
- An interface can’t be instantiated which means objects cannot be created.
- It supports multiple inheritances.
- It can’t inherit a class.
- It does not contain constructors.
- An interface contains only abstract methods.
- All methods and variables in an interface are declared as public.
Interface implementation in Java
// Example of interface in Java
interface interfaceExample{
static String name = "harry";
void display();
}
// class implements interface
class TestExample implements interfaceExample{
public void display(){
System.out.println("Hello, "+name+" !!!");
}
}
public class Main
{
public static void main(String[] args) {
TestExample test = new TestExample();
test.display();
}
}
Output
Hello, harry !!!
Also, read
Leave a Reply