How to declare an attribute in interface?

Asked

Viewed 927 times

2

How can I declare some attributes in an interface? Example, I have the interface called animal, I want her to have some attributes that class mamifero will implement, but the attribute I declare in the interface does not work.

interface Animal {
   protected $peso, $altura; 
}

The above code generates syntax error in Netbeans.

3 answers

5


What you really want is a abstract class and not an interface. If you really need it. Including by name, an animal should not be an interface since this mechanism is to indicate abilities and not objects.

Inheritance is not something to wear on anything, has certain criteria. And a protected member is also rare to be useful when done right. Most of the time you use this shouldn’t. Usually this particular hierarchy of the example serves to show how inheritance works, but it’s terrible to teach orientation to truth objects. In biology it’s very complicated to make hierarchies correctly, things aren’t as linear as they seem and modeling doesn’t usually work.

Understand more about abstract classes (there you go links for other things, including explaining the difference to the interface.

I don’t like the term attribute, I prefer field.

  • Thank you for the answer, so the correct thing in this case is not to use the interface but a class.

  • Yeah, an abstract class.

1

In your case, what you’re looking for is a Abstract Class, not an interface. I think it is important to make a brief distinction between Interfaces and Abstract Classes, since you seem to have some doubt in the difference between the functioning of both. Remember, both are concepts of Object-Oriented Programming.

I will exemplify using the Java language, but the operation is similar in PHP:


Interfaces


They function as contracts between you and your class, where you present certain warranties of class functioning; all classes that implement a certain interface must implement all methods (functions) declared in the interface, or the code will not compile. How methods are implemented, however, is not important, and there may even be an empty field of method.

Caelum’s booklet on Object Orientation brings an example simple about this type of interaction that helps to understand the concept; in the example, an interface called Account is created, and four methods are declared (each with its specific return)

public interface Conta {
  public double getSaldo();
  public void deposita(double valor);
  public void saca(double valor);
  public void atualiza(double taxaSelic);
}

After, we can create a Account class that will implement the Account interface, thus ensuring that it will have all the basic methods of an Account, regardless of its specialty.

class ContaCorrente implements Conta {

  // outros atributos e métodos

  public double getSaldo() {...}
  public void deposita(double valor) {...}
  public void saca(double valor) {...}
  public void atualiza(double taxaSelic) {...}
}


class ContaPoupanca implements Conta {

  // outros atributos e métodos

  public double getSaldo() {...}
  public void deposita(double valor) {...}
  public void saca(double valor) {...}
  public void atualiza(double taxaSelic) {...}
}

The interesting thing about Interfaces is that you can create contracts with multiple interfaces, indicating that your class should perform functionalities linked to different concepts. For example, a Puppy class can implement Animal, Biped, and Mamifero interfaces. This is the way some programming languages use to implement Multiple Inheritance.

It is important to mention, however, that each class that implements the interface should declare its own implementation of the methods.


Abstract Classes


In short, they function as Blueprints, that is to say, models working class. Abstract classes are one of the basic concepts of Inheritance. Abstract Classes cannot be initialized by itself, and there must always be a concrete class that inherits from the abstract class. Abstract classes make it possible to declare variables and standard methods for all classes they inherit from it. Thus, taking the example of the bank accounts mentioned above, it could declare standard data for all accounts (variables) and standard implementations of the declared methods:

Note: to facilitate the example, I will be using double to declare values, but you should not use double or float for values that need great precision because subsequent calculations with the variable decrease the accuracy of the variable can modify its value along the path, unless it uses methods to normalise the values and reduce the variation.

public abstract class Conta {
  private double saldo;
  private String nome;
  private String sobrenome;
  private int idade;

  public double getSaldo() {return this.saldo;}
  public String getNome() {return this.nome;}
  public String getSobrenome() {return this.sobrenome;}
  public int getIdade() {return this.idade;}
  public void deposita(double valor) {this.saldo += valor;}
  public void saca(double valor) {
    if (saldo > valor) 
      saldo -= valor;
    else System.out.println("Não é possível sacar esse valor");
  }
  public void atualiza(double taxaSelic) {}
} 

If when implementing a interface the class is required to create its own implementation of the declared methods, when inheriting of an abstract class, the methods declared in the abstract class are already readily usable by the class that inherited it. The concrete class assumes a role of daughter, who can use everything that was declared in her father.

Imagine your father has a car. The car is not yours, but you, as a child, can use the car to get out occasionally.

public class ContaPoupanca extends Conta {

  public ContaPoupanca (double saldo, String nome, String sobrenome, int idade) {
    this.saldo = saldo;
    this.nome = nome;
    this.sobrenome = sobrenome;
    this.idade = idade;
  }
  public void atualiza(double taxaSelic) {
    this.saldo *= 1 + taxaSelic;
  }
}

Unlike Interfaces, a class can inherit directly only from another class. There is no way a Puppy class inherits directly from Animal, Biped, and Mammal, since each of these classes may have statements of methods with identical signatures, but different implementations, which would cause conflicts during the program’s compilation.

-1

Good night, my friend.

This escapes a little from the concepts of POO, because an interface has to be a "purely abstract class", at most contain signatures of methods to be implemented according to the need of the class that extend them.

Currently we have the concept of "Default Methods", where an interface can have concrete methods, that is, already in its usual form, in some languages the attributes can even be declared, but this is not a recommended practice.

  • 1

    Read the question again.

  • I understood now I found on the internet no example of interface with attributes only methods, thanks for the answer.

  • @Maniero, thank you for complimenting. I was really wrong and I didn’t go into it. Now it became clear that he needed an abstract Class...

  • 1

    Search by default method in PHP

  • 1

    Putz, @Maniero. I saw here that PHP does not support Default Methods... Thanks for the info. It really was lack of attention from me, because I didn’t really read the question right (I answered as if it were solely and exclusively about POO)!

  • 1

    Even if it was generically OOP default method basically only exists in Java. And some people even consider OOP violation.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.