Interfaces, classes and constructors in java

前端 未结 2 832
悲&欢浪女
悲&欢浪女 2021-01-24 00:45

Here\'s something that bothers me regarding Interfaces and classes.

I\'m trying to do an implemataion for an interface called IPAddress by a class named IPAddressString.

相关标签:
2条回答
  • 2021-01-24 00:59

    A simple public class IPAddressString implements IPAddress will solve the problem.

    Another suggestion that jumped to my eye:

    It doesn't make any sense to declare the equals and toString() method in the interface because every object already has them. You wouldn't get a compile error if you didn't implement it.

    Furthermore, the equals method must always have the signature boolean equals(Object other), because only then it overrides the method of Object and will be called correctly at all time.

    0 讨论(0)
  • 2021-01-24 01:09

    You can implement IPAddress in IPAddressString. Although you are implementing all the methods of IPAddress interface in your IPAddressString class, you are not telling this to the compiler [which clearly cannot guess your intentions].

    change the definition of your class to :

    class IPAddressString implements IPAddress
    

    This should solve the problem in conversion.

    Now this line:

    IPAddress n1= new IPAddressString (n0,n1,n2,n3);
    

    will not give you problems since the hierarchy is established. And you can peacefully return n1.

    0 讨论(0)
提交回复
热议问题