Do interfaces have a constructor in Java?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 09:53:04

问题


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.



来源:https://stackoverflow.com/questions/40813160/do-interfaces-have-a-constructor-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!