简体   繁体   中英

How to access variables of a class from another file in JAVA

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.

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();

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

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