prinsJoe
prinsJoe

Reputation: 693

Creating Variables in Interfaces (Java)

So, I can create a simple interface in C# like so:

 public interface IAnimal {
      int HumanYearAge { get; set; }
      int AnimalYearAge { get; }
 }

And then I can make an interfacing class like this:

 public class Dog: IAnimal {
      public int HumanYearAge;
      public int AnimalYearAge
      {
        get { return Age * 20; }
      }
 }

And then in the Program I can instantiate a Dog that has a certain "HumanYearAge" and a certain "AnimalYearAge" after calculations. In Java, I have found many ways to create variables, most of which look like this:

 public interface myInterface {
      AtomicReference<String> Name = new AtomicReference<String>("John Doe");
      //Or they look something like this:
      public final int Name = 0;
 }

How can I create a modifiable variable inside of a Java interface that can be PASSED DOWN (not assigned on the spot) to a class that, when instantiated as an object, can be assigned a value?

Upvotes: 0

Views: 145

Answers (2)

cangrejo
cangrejo

Reputation: 2202

Interfaces in Java do not have attributes. You need to use an abstract class.

You can have one like this.

public abstract class Animal{

    private int animalYearAge;

    public Animal(int animalYearAge){
        this.animalYearAge = animalYearAge;
    }

    public void setAnimalYearAge(int age){
        this.animalYearAge = age;
    }

    public int getAnimalYearAge(){
        return animalYearAge;
    }

    public abstract int getHumanYearAge();        

}

Then, you can define a concrete animal like this, for example.

public class Dog extends Animal{

    public int getHumanYearAge(){
        return this.getAnimalYearAge() * 7;
    }
}

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39447

These are not variables but are called properties in C#. And they are basically methods (in Java terms) - a getter and a setter (or one of those). I would add getHumanYearAge (maybe also setHumanYearAge) method in your interface. The classes implementing the interface will need to define its body (or their bodies). And you get the same thing as in C#. It's just that Java is more verbose (properties in C# are more concise).

Upvotes: 1

Related Questions