I know that interfaces in Java are handled by the virtual machine as abstract classes. So, every class in Java, abstract or not has a constructor. Does this mean that interfaces have a constructor too? Because too me on one hand makes sense to have a constructor since they are abstract classes. On the other hand it doesn´t make sense since interfaces don´t have any attributes to initialize. So how does it actually work?
问题:
回答1:
Interfaces don't have constructors. Their implementations do.
回答2:
All an interface is:
interface MyInterface{
void addNumber(int amount);
void subtractNumber(int amount);
int getNumber();
}
You don't "run" an interface, and an interface isn't something you create objects out of.
The class that implements your interface does have a constructor though:
class MyNumber implements MyInterface{
private int myNumber;
//Here is your constructor, called when you instantiate it.
myNumber(int number){
myNumber = number;
}
//Now you need to add the methods in your interface
public void addNumber(int number){
myNumber = myNumber + number;
}
public void subractNumber(int number){
myNumber = myNumber - number;
}
public int getNumber(){
return myNumber;
}
}
So no, interfaces do not have constructors. Hope this helps!
Edit: When you create your object, you call your constructor:
MyNumber number = new MyNumber(5); //Calls the constructor and creates a new MyNumber with the value of 5.
number.addNumber(6); //Adds 6 to your number, it is now 11.
number.subtractNumber(3); //Subracts 3 from your number, it is now 8.
number.getNumber(); //returns the value of myNumber inside of your MyNumber object, which is 8.
Edit 2: I want to elaborate a little more on interfaces. You are correct in saying they don't have any attributes to initilize. They have methods to IMPLEMENT. If you have a "move" method in your interface, it can apply to many, many different things. Cars, dogs, boats, planes, sloths and snakes all move, but how do they move? Cars move faster than sloths, so it moves differently. When you create classes for whatever you need to move, you can change that move method and tailor it to the situation you need. That's the point of an interface, flexibility.