Java Tutorial series - Getters and Return values
Following up with the Java Tutorial series, we will be covering Getters and return values in this post. By using Getters and return type we can implement Encapsulation, one class can use the methods and values from other class by not going in details, Let's see how it is implemented in the example given below -
Getters and Return Values-
- Getter always have a return type
- Getter will never have any parameters.
class Person {
String name;
int age;
int calculateYearsLeftToRetirement() {
int yearleft = 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;
int age = person1.getAge();
String name = person1.getName();
System.out.println("Age is :"+ age);
System.out.println( "Name is "+ name);
}
Comments
Post a Comment