Sunday, May 1, 2016

Getter Methods


When writing a method you must define what it is beforehand. If you define a method as Void it won’t return anything. In order to get a method to return a value you must define the type. The second thing you must do is type return then that variable, at the end of the method. Whenever you call that method to an object it calls that return value. This allows you to use that value in your main method.

A nice way to get instance variables from classes, is to make a getter method that returns that variable. Getter methods are important when you start to make instance variables private. Which means you won’t be able to use that instance variable in your main method. So you can make a getter method for that variable then use it wherever you want. Below is an example when I used getter methods to assign variables age and name.

class Person {

      String name;

      int age;

     

      void speak() {

            System.out.println("My name is:" + name);

      }

      int calculateYearsToRetirement(){

            int yearsLeft = 65 - age;

            return yearsLeft;

      }

      int getAge() {

            return age;

      }

      String getName(){

            return name;

      }

}



public class App {



      public static void main(String[] args){

            Person person1 = new Person();

            person1.name = "joe";

            person1.age = 25;

   

            person1.speak();

           

            int years = person1.calculateYearsToRetirement();

            System.out.println("years till retirements " + years);

            int age = person1.getAge();

            String name = person1.getName();

           

            System.out.println("Name is: " + name);

            System.out.println("Age is: " + age);

      }    

}

No comments:

Post a Comment