简体   繁体   中英

one more question about Interfaces, classes and constructors in java

One more question that relates to this interface .

Let's say that I would like to implement the interface now with arrays.

Here's a part of my code:

import java.util.Arrays;

class IPAddressShortArray implements IPAddress {

private int [] IpAdress;

public  IPAddressShortArray(int num1, int num2, int num3, int num4) {
    this.IpAdress[0] =num1 ;
    this.IpAdress[1]=num2;
    this.IpAdress[2]=num3;
    this.IpAdress[3]=num4;

}

public String toString() {
    return IpAdress.toString();

}

public boolean equals(IPAddress other) {

    boolean T= true;
    for (int i=0;i<=3;i++){
        if (this.IpAdress[i]!=other[i]){
            .......

        }
    }
}

There's a compiler error saying that The type of the expression must be an array type but it resolved to IPAddress , but IpAddress right now is represented by array, so what's the problem? why can't I refer to other[i] if I have this implementation?

I know that equals should not be implemented again. Let's assume that I want to implement it.

The whole point of interfaces is that they hide implementation details. You're using a variable that is declared as of type IPAddress but then trying to use it as an IPAddressShortArray .

A proper implementation would be to add a method to the interface to get each octet of the address, eg:

public int getOctet(int octetIndex)

In the IPAddressShortArray class the implementation of this method would look like:

public int getOctet(int octetindex) {
  return this.IpAddress[octetindex];
}

Then in your equals method you would use other.getOctet(i) instead of other[i] or other.IpAddress[i] .

other is still an IPAddress, not an array. Also, you're never initializing the IpAdress member (you need new int[4] ), and you spelled it wrong.

Other is type IPAddress which isn't an array. I'd find the code easier to use if IpAddress started with a lower case character as that is a very common convention for Java variables, classes generally start with a capital.

 if (this.IpAdress[i]!=other[i]){

other is of type IPAddress , so you can't treat it like an array.

Did you mean

 if (this.IpAdress[i]!=other.IpAdress[i]){

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM