
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why an interface doesn\\\\\'t have a constructor whereas an abstract class have a constructor in Java?
Interfaces in Java are used for defining a contract that classes can implement. They can contain method signatures, default methods, static methods, and constants. we must implement the methods defined in the interface in the implementing class.
Constructor in an Interface
A Constructor is to initialize the non-static members of a particular class with respect to an object.
- An Interface in Java doesn't have a constructor because all data members in interfaces are public static final by default, they are constants (assign the values at the time of declaration).
- There are no data members in an interface to initialize them through the constructor.
- In order to call a method, we need an object, since the methods in the interface don't have a body there is no need for calling the methods in an interface.
- Since we cannot call the methods in the interface, there is no need of creating an object for an interface and there is no need of having a constructor in it.
Example
Following is an example of an interface in Java:
interface Addition { int add(int i, int j); } public class Test implements Addition { public int add(int i, int j) { int k = i+j; return k; } public static void main(String args[]) { Test t = new Test(); System.out.println("k value is:" + t.add(10,20)); } }
Why a Abstract Class Has a Constructor?
An abstract class can have a constructor because it can be instantiated indirectly through its subclasses. The constructor in an abstract class is used to initialize the state of the object when a subclass is instantiated. This allows the abstract class to set up any necessary fields or perform any setup that is common to all subclasses.
Example
Following is an example of an abstract class in Java:
abstract class Animal { String name; Animal(String name) { this.name = name; } abstract void sound(); } class Dog extends Animal { Dog(String name) { super(name); } void sound() { System.out.println(name + " barks"); } } public class Test { public static void main(String args[]) { Dog d = new Dog("Buddy"); d.sound(); } }
When you run the above code, the output will be:
Buddy barks