Home > Software engineering >  How to access variables of a class from another file in JAVA
How to access variables of a class from another file in JAVA

Time:07-28

I am new to java and I am trying to work a simple program. I have created a class and defined the variables like this

public class Animal {

    private String age;
    private String color;
    Breed breed;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Breed getBreed() {
        return breed;
    }

    public void setBreed(Breed breed) {
        this.breed = breed;
    }
}

class Breed {
    private String afador;
    private String afaird;
    private String aussiepom;

    public String getAfador() {
        return afador;
    }

    public void setAfador(String afador) {
        this.afador = afador;
    }

    public String getAfaird() {
        return afaird;
    }

    public void setAfaird(String afaird) {
        this.afaird = afaird;
    }

    public String getAussiepom() {
        return aussiepom;
    }

    public void setAussiepom(String aussiepom) {
        this.aussiepom = aussiepom;
    }
}

I want to access the variables in class "BREED" from ANOTHER file, with "animal.breed..." which does not work. How can I access the variables in the "BREED" class?? I am not sure if it is because I have the getter and setters in this file, kindly advise on the same.

CodePudding user response:

You must be user the get method:

Animal animal = new Animal();
Breed breed = animal.getBreed();

Another option is declare public the breed attribute, but not is a good practique

CodePudding user response:

I think I see what you are trying to do, however, you did not provide any sample code so I will be answering based on assumptions.

To start, you are trying to access a variable from inside of the Breed class through the getter methods. Lets look at some code.

// I'm assuming this is similar to what you have set up.

// Make a new breed
Breed breed = new Breed();

// Setting the breed to Afador through your methods
breed.setAfador("Afador");


// Make a new animal
Animal animal = new Animal();

// Set our animal's breed to our newly made breed
animal.setBreed(breed);

You mentioned you got the getBreed() method to work, so you must have done something along the lines of

animal.getBreed();

You then mentioned you could not get getAfaird() method to work, so I assume you did something like this

animal.getAfaird();

This does not work since getAfaird() does not exist within the Animal class but rather the Breed class. You can only use this getAfaird() method on Breed objects. So you would want to do something like this

animal.getBreed().getAfaird();
  • Related