Unknown user
Unknown user

Reputation: 45321

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.

Upvotes: 0

Views: 111

Answers (4)

Dave Costa
Dave Costa

Reputation: 48121

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, e.g.:

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].

Upvotes: 1

EboMike
EboMike

Reputation: 77752

 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]){

?

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

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.

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

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.

Upvotes: 0

Related Questions