Posts

Showing posts with the label Getters

Java Tutorial Series - Setters and 'this' Keyword

Now we have already understood the concept of getters in Java, we will be diving deep into the concepts of setters and 'this' keyword used in Java. Setters and 'this' keyword -  Consider below example where we are using getters, setters and 'this' keyword. class Frog { private String name; private String age; public void setAge(int age) { this.age = age; } public void setName(String Name) { this.name = name; } public String getName() { return name; } public int getAge() { return age; } public void setInfo(String name, int age) { setName(name); setAge(age); } } public class App { public static void main(String[] args) { Frog frog1 = new Frog(); frog1.setName("Charlie"); frog1.setAge(22); System.out.println(frog1.getName()); } }

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