Exercises - Creating Java objects and methods


 

13. Exercises - Creating Java objects and methods

13.1. Create a Person class and instantiate it

Create a new Java project called com.vogella.javastarter.exercises1 and a package with the same name.

Create a class called Person.

Add three instance variables to it, one for storing the first name of the person, one for storing the last name and one for storing the age of the Person.

Use the constructor of the Personobject to set the values to some default value.

Add a toString method as described by the following coding and solve the TODO. This method is used to convert the object to a String representation.

@Override
public String toString() {
    // TODO replace "" with the following:
    // firstName + " " + lastName
    return "";
}

Create a new class called Main with a public static void main(String[] args). In this method create an instance of the Person class.

13.2. Use constructor

Add a constructor to your Person class which takes first name, last name and age as parameter. Assign the values to your instance variables.

In your main method create at least one object of type Person and use System.out.println() with the object as parameter.

13.3. Define getter and setter methods

Define methods which allow you to read the values of the instance variables and to set them. These methods are called setter and getter.

Getters should start with get followed by the variable name whereby the first letter of the variable is capitalized.

Setter should start with set followed by the variable name whereby the first letter of the variable is capitalized.

For example, the variable called firstName would have the getFirstName() getter method and the setFirstName(String s) setter method.

Change your main method so that you create one Person object and use the setter method to change the last name.

13.4. Create an Address object

Create a new object called Address. The Address should allow you to store the address of a person.

Add a new instance variable of this type in the Person object. Also, create a getter and setter for the Addressobject in the Person object.

Comments

Popular posts from this blog

How to Hack WhatsApp Chats

Installation of Java

Integrated Development Environment