Java and Back Again

A beginners tale…part 4

Robert M Ricci
Apr 8 · 2 min read
Photo by Brooke Lark on Unsplash

Welcome to the fourth part of my journey with java. In the first part, I talked a little about the history and some basic principles. With the second part, I went into state and instances, with some time explaining a little about object-oriented programming. In the third part, we talked about arrays and ArrayLists. In this part, we are going to talk about encapsulation, and the different ways methods can be accessed.

The aim of encapsulation is to create small bundles of logic, by keeping implementation details hidden from other classes. There are a few different ways in which we can do this. The one I will talk about is with the public and private keywords. Now we have all seen the public keyword before in previous posts. Which allows access from any class. Meanwhile private restricts access to only the class that made the declaration.

public class dontPanic {

private String name;
private int number;
}

A way the access those private variables would be to use an accessor method. Accessor methods return the value of a private variable. This would allow a class to access the value of the variable without actually having direct access to the variable itself. These methods take no parameters and have a return type that matches the type of the variable they are accessing. You will notice I used the this keyword. I will explain that a little later on.

public class dontPanic {

private String question;
private int answer;
public int getAnswer() {
return this.answer;
}
}

If we would want to change the value of a private variable we could use a mutator method. These allow other classes the ability to modify a variable without having direct access to it. A mutator method takes in one parameter with a type that matches the type of the variable it is modifying. There is nothing returned.

public class CheckingAccount{
private int question;


public void setQuestion(int newQuestion){
this.question = newQuestion;
}
}

The this keyword is used to differentiate between an instance variable and a local variable. Variable with this represents the instance. You can also use the this keyword with method calls.

public class dontPanic {

private String question;
private int answer;
public int getAnswer() {
System.out.print("42");
}
public String askQuestion() { this.getAnswer();
System.out.println("What is the meaning of Life, the
Universe, and Everything");
}
}

The last thing I wanted to mention is the difference between instance and local variables. An instance variable can be used is declared within a class, but outside a method. Whereas a local variable can only be used within a method.

That’s all for this post. I hope you have a mild grasp of encapsulation. Check back next week, for the fifth and final part of this series.

Geek Culture

Proud to geek out. Follow to join our 1M monthly readers.