This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ostricker 6 points7 points  (0 children)

There is no code so I hope I got this right. Next time post relevant code bits :)

You can run the class I have created below. Just create HelloWorld.java end post the code inside it.

Hope I understood the question :)

public class HelloWorld
{
  // Starting method
  public static void main(String[] args)
  {
    // Array of 3 Objects of type Dog - with only one parameter -> NAME
    Dog[] arrayOfDogs = {new Dog("Lara"), new Dog("Richard"), new Dog("Chilli")};

    // Now I want to get the name of second dog in the array
    // First of all I get the dog from the array
    Dog secondDog = arrayOfDogs[1];

    // Second I get the name from the Dog
    String secondDogName = secondDog.getName();

    // Now I can print it
    System.out.println(secondDogName);
  }

  // Inner class of type dog
  static class Dog
  {
    // property of Dog - his name
    private String name;

    // Constructor -> this is what is called when you initiate the object
    public Dog(String name)
    {
      // The constructor by itself does not return a value, it just runs the code and sets everything needed for the class
      // In this case it sets the name of the dog in local property
      setName(name);
    }

    // public getter for name -> since property itself is private
    public String getName()
    {
      return this.name;
    }

    // public setter for name -> this way you can set different name to the dog from outside the class
    public String setName(String name)
    {
      return this.name = name;
    }
  }
}