Matthew
Matthew

Reputation: 91

How do you bundle getters in Java?

public String getPet() {
    public String getName() {
        return name;
    }
    public String getType(){
        return type;
    }
    public String getDescription() {
    }
    return description;
 }

I would like to bundle three getters into one, so that getPet() gets getName(), getType(), and getDescription(). I typed this out, but there is something wrong with my syntax that I cannot figure out.

Upvotes: 0

Views: 78

Answers (2)

What you want is redundant, but here it comes another funny but valid option:

public Pet {
...
  public Pet getPet(){
    return this;
  }
}

Then you can access all your methods from getPet(), but, as I said this is redundand:

Pet p = new Pet();
Pet q = p.getPet();

So you can access, from getPet() all of the other methods:

p.getPet().getName();
p.getPet().getType();
p.getPet().getDescription();

But that's redundant, since you can access these directly:

p.getName();
p.getType();
p.getDescription();

It is pretty probable, there's some misunderstanding on the Object Oriented fundamentals you're trying to implement. May I suggest, take a read to: https://docs.oracle.com/javase/tutorial/java/concepts/index.html

Upvotes: 1

rhowell
rhowell

Reputation: 1187

You cannot directly have nested methods in Java. You can call as many methods as you want inside of a method though.

So you could have something like this

public Pet getPet() {
    getName();
    getType();
    getDescription();
    // create a pet from these method calls and return it i suppose?
}

public String getName() {
    return name;
}
public String getType(){
    return type;
}
public String getDescription() {
    return description;
}

Like others have said though, there is no real reason that I could see to do this.

Upvotes: 2

Related Questions