Learn Java Tutorial for Beginners (Video), Part 15: Getters and Return Values

Using get methods or "getters" in your Java classes, and how to return values from methods in general.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:

 
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);
    }

}

 
Years till retirements 40
Name is: Joe
Age is: 25