Get startedGet started for free

Defining a POJO

Building a POJO is about creating a straightforward Java class following a few rules. POJO classes are simple and independent; they don't extend other classes or implement interfaces. The main task is to define the fields and create getter and setter methods to access them. Here, you create a POJO for transporting savings account data in a Java application.

This exercise is part of the course

Data Types and Exceptions in Java

View Course

Exercise instructions

  • Add a field balance of type double to hold the account balance value, making sure to choose the correct access.
  • Define a getter method to return the balance field value.
  • Define a setter method to allow the balance field to a new value.
  • In the setter method, set the balance field to the setter's argument.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class Test {
  public static void main (String[] args){
  	SavingsAccount account = new SavingsAccount();
    account.setAccountNo("12345");
    account.setBalance(50000.00);
    System.out.println("Account " + account.getAccountNo() + " has balance of: " + account.getBalance());
  }
}

public class SavingsAccount {
	private String accountNo;
    // Add a balance field
	____ ____ ____;

	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

    // Define a balance getter method
	____ ____ ____() {
		return balance;
	}

    // Define a balance setter method
	public ____ setBalance(double balance) {
    	// Set the balance field
		____.____ = ____;
	}
}
Edit and Run Code