Methods and Encapsulation Tutorial

Welcome to the Java Methods and Encapsulation tutorial offered by Simplilearn.  The tutorial is a part of the Java Certification Training Course.

Let us begin by looking into the objectives of this methods and encapsulation tutorial.

Objectives

In this methods and encapsulation tutorial, we will be able to -

  • Explain what a Java method is

  • Apply static keyword to the method

  • Create and overload constructors

  • Apply access modifiers to restrict the scope of a class, data member, method, or constructor

  • Apply encapsulation principles to a class

  • Pass objects reference and primitive values to methods

Let us begin with the Java methods in the next section.

Java Methods

A method is a collection of statements that are grouped together to perform an operation.

<modifier>* <return_type> <name> ( <argument>* )

{

<statement>*

}

The reason we would create a method is so that you could reuse it as and when required. The method is also more for the black box where you pass a value to it, it performs an operation and returns a value.

To declare a method you need a modifier which would be an access modifier. Then, we provide the return type in terms of the what data type it would return, followed by the name of the method and a list of arguments as required.  

The <modifier> segment is optional and carries a number of different access modifiers, including:

  • public: A method that can be called from other code

  • private: A method that can be called only by other methods in a class

  • protected: A method that can be called within a method in a class

  • default: A variable or method declared without any access control modifier that is available to any other class in the same package

The <return_type> indicates the type of value to be returned by a method.

The name can be any legal identifier, with some restrictions based on the names that are

already used in the program.

The <argument> list allows argument values to be passed into a method.

In the next section, let us look at the Java Methods example.

Java Methods Example

Let us look at an example.

public class Dog

{

private int weight;

public int getWeight() {

return weight;

}

public void setWeight (int newWeight) {

if (newWeight > 0) {

weight = newWeight;

}

}

}

Here, we do a simple validation to check if the new weight is greater than zero, only then we assign it to the weight data member of the class. From this example, we can say that generally, the data members of the class would be private, and the methods in your class would be public.

In the next section, let us look at the static keyword in Java.

Static Keyword in Java

The static keyword is a non-access modifier. Static methods can be called without creating an object of the class. It can be applied with variables, methods, blocks, and nested class. Also, they belong to the class, and not the instance of the class and hence such methods can typically be called only prefixed with the name of the class.

In the next section, we will look at the static method in Java.

Static Method in Java

The static method enables you to apply the static keyword with any method. It belongs to a class rather than the object of the class. It can access a static data member and can change the value of it.

In the next section, let us look at an example of the static method.

Java Static Method Example

Let us now look at an example of the static method. Here, we have a student class, with roll number, name, college as parameters. The college is common for all the students and hence if we create three different objects of the student class or two different objects of the student class say S1 and S2 we would have different values for roll number and name.   

class Students3

{

int rollno;

String name;

static String college = “MGT";

static void change(){

college = “MGIT";

}

Students3(int r, String n){

rollno = r;

name = n;

}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){

Students3.change();

Students3 s1 = new Students3 (111,“Paul");

Students3 s2 = new Students3 (222,“Martha");

Students3 s3 = new Students3 (333,“Bob");

s1.display();

s2.display();

s3.display();

}

}

Output:

111 Paul MGIT

222 Martha MGIT

333 Bob MGIT

Even though we did not pass specific college names, all the three objects picked up the same college name since it was a static variable and that got assigned in a static method.  

In the next section, we will look at some important points of the Java static methods.

Want to join the high-earners club? Enroll in our Java Certification Course today

Java Static Methods —Important Points

Some of the important points to be noted in the static method are -

  • You cannot override a static method, but you can hide it. For a method to be overridden, it must be non-static. Overriding is a feature of polymorphism or perhaps an OOPS feature. It is a pillar of OOPS, which is an implementation of the polymorphism OOPS concept.

  • The main() method is a static method because the JVM does not create an instance of a class when executing the main method.

  • You can use a static method as a class method.

  • You should access methods that are static using the class name rather than an object reference.

Let us go to the final keyword in the next section.

final Keyword in Java

The final keyword is a reserved keyword in Java that stops the value change, method overriding, and Inheritance.

It can be applied to:

  • Methods

  • Classes

  • Member variables

  • Local variables

If the final keyword is applied to the Methods, then, that method cannot be overridden; If it is applied to the Classes, we cannot inherit further from that class and we cannot implement the OOPS feature of inheritance; If the final keyword is applied on Member variables, then, we cannot change the value of that variable as it becomes a constant value that the variable will hold irrespective of the Member variable of the class or the Local variable that is defined inside the method.  

Some of the final keywords include -

final Class: You can apply the final keyword to a class to form a final class. Once you do this, that class cannot be subclassed or inherited.

For example, java.lang.String. This is a final class for security reasons.

final Method: You can mark a method as final.

Once a method is made final, it cannot be overridden in the child classes.

final Variable: You can apply the final keyword to a variable to make it constant. When the value of the final variable is tried to change, it will result in a compiler error.

Here we find a private static final double and the variable name is assigned a value. Since this is final, we cannot change the value of the variable, it becomes a static constant inside the class. We can only define, as the value is a fixed value.

public class Bank {

private static final double DEFAULT_INTEREST_RATE=3.2;

// more declarations

}

If we have the interest rates or the value of pi in a mathematical calculation, we can define that as final so that these values do not undergo any changes further in the code.  

Let us talk about constructors next in Java in the next section.

Create and Overload Constructors in Java

A constructor is a set of instructions designed to initialize an object.

So in case, we have some default values that our object should hold; the moment we create a new object of the class, we should ensure that the developer does not forget to initialize those default values. For this, the constructors have been provided, so that the initialization of these values can happen within these constructors.

This is also a good feature to avoid the null reference error that we generally encounter in cases where there are some values or data members in the class that are uninitialized and when we allow the user to create an object of the class, some other developer may get a null reference error saying that this particular array or object was not initialized and yet you were able to create an object of the class and access some of the data members.

Parameters can also be passed to the constructor in the same way as for a method; this means that the parameters can also be passed to the constructor in the same way as we do to a method, so that, when the object is initialized you can pass some default values that can be assigned to the object.

For example, if we are creating the student object, there itself during the initialization line, we can pass the student id and the student name. Therefore, the moment the student object is created it will be initialized with an id and a name.

Basic declaration of a constructor:

[<modifier>] <class_name> (<argument>* )

{

<statement>*

}

This code gives the basic declaration of a constructor, the access modifier, the name of the class, and the argument list. Thus, the constructor always has the same name as that of the class.

Valid modifiers are public, protected, and private. Valid modifiers can be made private so that nobody would be able to create an object of the class because your constructor would be a private constructor.

When the constructor is made public, we allow users to initialize the class because a constructor will automatically fire, when the object of the class is created. You can also mark it as protected.

The <argument> list is the same as that used for method declarations. You can provide any number of argument declarations as per your requirements as you do for a regular class method.

Constructors can also be declared with parameters. In the next section, let us learn about the default constructors in Java.

Default Constructors in Java

A constructor with no arguments having the name of the class without a return type is a default constructor. This enables us to create object instances with the new keyword. Once again it fires the very moment a new instance of the class is created.

On doing this, the default constructor fires and we can use the default constructor to set some default start values for data members in our class. A user added constructor declaration to a class always overrides the default constructor.

Thus, in case we have not provided a constructor in our class, the system will automatically generate a default constructor. Implicitly, we will not see it in the code and initialize the object. Depending on the data type used in the class, the number of variables, if it is in the string, or int it will accordingly assign it to zero or null.

In the next section, let us look at an example of the default constructors in Java.

Default Constructors Example

Given below is an example of a default constructor.

class Test

{

public void disp()

{

System.out.println(“Display All”);

}

public static void main(String args[]){

Test t1=new Test();

t1.disp();

}

}

}

In the next section, let us learn about the Java Access Modifiers.

Java Access Modifiers

Access modifiers in Java set access level for classes, variables, methods, and constructors. They have four levels.

 

The first level is the package level. Here, we can control whether the class can be accessed out of our package and inside another package.

We can set the package level access if we are not adding any specifier, default access or no modifiers at all or private.

For example, if the variable is marked public, it is accessible everywhere.

If the variable is marked protected, it is accessible in the same class. It is accessible in child classes of that class and it is accessible in all the classes within that package only. It is inaccessible to classes outside the current package.

If we do not give any modifier by default, a default modifier gets applied to that data member and they are accessible only within the class and within the current package.

The last one is the private modifier. If we give anything as private, it is accessible only within the class and not accessible within other classes in the same package or within the subclass. This is the broad perspective of the access levels for the access modifiers present in java.

public access modifier:

The public access modifier is accessible everywhere. It has the widest scope among all modifiers.

public class employee

{

<statement>

}

protected access modifier:

The protected access modifier is accessible within and outside the package but through inheritance only.

protected access modifier:

public class A{

protected void mesg(){

System.out.println("Hello");

}

}

private access modifier:

The private access modifier is accessible only within the class.

class D

{

private int data=20;

private void mesg(){

System.out.println("Hello Java");

}

}

In the next section, we will learn about Java Encapsulation.

Java Encapsulation

Java Encapsulation is a methodology of hiding certain elements of the implementation of a class but providing a public interface for the client software. To achieve encapsulation in java, you need to-

  • Declare the variables of a class as private, and

  • Provide public getter and setter methods to modify and view the variable values

Let us look at an example of this encapsulation principle.

Given below is an example of hiding data that will help you understand encapsulation better:

MyDate

-date : long

+getDay() : int

+getMonth(): int

+getYear(): int

+setDay(int) : boolean

+setMonth(int) : boolean

+setYear(int) : boolean

-isDayValid(int) : boolean

To understand encapsulation, think of it as a black box. The reason we have encapsulation is because if there are any changes that need to be implemented in the code of your class, like, if the customer comes to you with a change request and the entire code is visible externally to other classes or modules or subsystems, the moment there are changes made to your class, all the other classes will get impacted at the cost of testing the entire code base and there is a risk of some other code breaking if you make a change to your class.

Encapsulation prevents this. Since our code is encapsulated within a class, any change that we make to the method or the code inside the method will never impact any subsystems using that code. This is because, if suppose we have a function called calculate tax, all we can do from the outside when we are using a class is to create an object of the class and call it to calculate the tax.

There is no way that we would know what is the process of tax calculation taking place in the third party class. The moment we are exposed to that, any change made by the user makes the client or the application using that API or that class method will simply break. To prevent this, we always keep the class method same.

Therefore, the method continues to remain to calculate tax and the other classes of the other subsystems just adhere to that method name. The moment the method name remains the same, the internal implementation of the method can always change because that will have zero impact on the subsystems of the client code.

In order to achieve encapsulation, we either declare the variables private, so that they cannot be accessed outside or we make use of methods, because, when we declare a method, the code inside is encapsulated within the class and this is hidden from those who are calling it.

Thus, only the developers who are calling your code know what the code does. They cannot see how the process is happening. The client subsystem would need to be modified if the code in the class is modified and also the cost and time required to do that will be higher. So, the end user would have to wait much longer for the software to get delivered.

In the next section, we will look at Passing Objects Reference and Primitive Values to Methods in Java.

Passing Objects Reference and Primitive Values to Methods in Java

Let us learn about Passing Object by Reference in Java.

All parameters are passed by values, but objects are always manipulated through reference variables in Java. We can say that objects are passed by reference.

Let us understand this with an example. Here, we have a class test1 wit an integer value of 10. Next, we have the class test parameter where we are creating the object of this class and executing a method called amethod.

Class Test1

{

public int i = 10;

}

public class TestPar{

public static void main(String argv[ ])

{

TestPar p = new TestPar();

p.amethod();

}

public void amethod()

{

Test1 t = new Test1();

t.i=10;

System.out.println("Before another = "+ t.i);

another(t);

System.out.println("After another = "+ t.i);

}

//End of a method

public void another(Test1 t){

t.i = 20;

System.out.println("In another = "+ t.i);

}

//End of another

}

Output:

Before another = 10

In another = 20

After another = 20

This is an example of passing object references which means we are passing pointers to objects which are pointing both to the same memory location.

In the next section, we will learn Primitives as Method Parameters in Java.

Primitives as Method Parameters in Java

When you pass primitives to a method, they are considered passed by value. A method works with its own copy and no modifications reflect outside the method.

Let us understand with an example. Here, we are creating an object of the class, initializing the value ‘i’ and we print the value of ‘i’.

public class Par1

{

public static void main(String argv[])

{

Par1 p = new Par1();

p.amethod();

}//End of main

public void amethod()

{

int i=10;

System.out.println("Before another i= " +i);

another(i);

System.out.println("After another i= " + i);

} //End of amethod

public void another(int i)

{

i+=10;

System.out.println("In another i= " + i);

} //End of another

}

Output:

Before another i= 10

In another i= 20

After another i= 10

Thus primitive types are not pointers, they are typically stored on the stack. They are not the pointers on the stack that point to the value on the heaps and hence they are always passed by value. Thus, passing by value means, a copy of that variable is created in memory, it is replicated and then passed.

Summary

Let us summarize what we have learned in this methods and encapsulation tutorial -

  • The Java method is a collection of statements that are grouped together to perform an operation.

  • The static keyword in Java is used for memory management. We can apply Java static keyword with variables, methods, blocks, and nested class.

  • A constructor is a set of instructions designed to initialize an instance. Parameters can be passed to the constructor in the same way as for a method.

  • Access modifiers set access levels for classes, variables, methods, and constructors. The four access levels are the package, the default, no modifiers, and private.

  • Encapsulation is the methodology of hiding certain elements of the implementation of a class but providing a public interface for the client software.

Conclusion

With this, we come to an end to the methods and encapsulation tutorial.
 

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 14 Dec -2 Feb 2020, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*