Core Java
Lesson 6—Methods and Encapsulation
© Simplilearn. All rights reserved.
Learning Objectives
At the end of this lesson, you should 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
Methods and Encapsulation
Topic 1—Java Method
Method
A method is a collection of statements that are grouped together to perform an operation.
<modifier>* <return_type> <name> ( <argument>* )
{
<statement>*
}
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
Method (Contd.)
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.
Method Example
public class Dog
{
private int weight;
public int getWeight() {
return weight;
}
public void setWeight (int newWeight) {
if (newWeight > 0) {
weight = newWeight;
}
}
}
Methods and Encapsulation
Topic 2—Static Keyword in Java
Static Keyword
Static keyword is a non-access modifier. Static methods can be called without creating an object of
class.
It can be applied with variables, methods, blocks, and nested class.
It belongs to the class, not the instance of the class.
Static Method
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.
Static Method Example
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
}
Static Method—Important Points
You cannot override a static method, but you can hide it.
For a method to be overridden, it must be non-static.
The main() method is a static method because the JVM does not create an instance of a class when
executing a 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.
final Keyword
final keyword is a reserved keyword in Java that stops value change, method overriding, and
inheritance.
It can be applied to:
Methods
Classes
Member variables
Local variables
final Keyword (Contd.)
final Class: You can apply the final keyword to a class to form a final class.
Once you do this, the class cannot be subclassed.
Example: java.lang.String. This is a final class for security reasons.
final Method: You can mark a method as final.
Once you make a method final, it cannot be overridden.
final Variable: You can apply the final keyword to a variable to make it a constant.
If you try to change the value of a final variable, it will result in a compiler error.
public class Bank {
private static final double DEFAULT_INTEREST_RATE=3.2;
// more declarations
}
Methods and Encapsulation
Topic 3—Constructors in Java
Create and Overload Constructors
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.
Basic declaration of a constructor:
[<modifier>] <class_name> (<argument>* )
{
<statement>*
}
Valid modifiers are public, protected, and private.
<argument> list is the same as that used for method declarations.
Constructors can also be declared with parameters.
Default Constructors
A constructor with no arguments is known as default constructor
It enables you to create object instances with new xyz();
A user-added constructor declaration to a class overwrites the
default constructor.
Default Constructors Example
class Test
{
public void disp()
{
System.out.println(“Display All”);
}
public static void main(String args[]){
Test t1=new Test();
t1.disp();
}
}
}
Core Java
Topic 4—Access Modifiers
Access Modifiers
Access Modifiers set access levels for classes, variables, methods, and constructors.
They have four levels—the package, the default (no specifier), no modifiers, and private.
public
protected
Default or no modifier Access Levels
private public Y Y Y Y
protected Y Y Y N
Class only
no modifier Y Y N N
Class and package
private Y N N N
Class, package, and subclasses
All classes
Access Modifiers (Contd.)
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. public class A{
protected void mesg(){
System.out.println("Hello");
}
}
Access Modifiers (Contd.)
private access modifier:
The private access modifier is accessible only within class.
class D
{
private int data=20;
private void mesg(){
System.out.println("Hello Java");
}
}
Core Java
Topic 5—Encapsulation
Encapsulation Principle
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
Provide public getter and setter methods to modify and view the variable values
Encapsulation Principle (Contd.)
Example for hiding data:
MyDate
-date : long
+getDay() : int
+getMonth(): int
+getYear(): int
+setDay(int) : boolean
+setMonth(int) : boolean
+setYear(int) : boolean
-isDayValid(int) : boolean
Core Java
Topic 5—Passing Objects Reference and Primitive Values to Methods
Passing Object by Reference
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.
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; Output:
System.out.println("In another = "+ t.i); Before another = 10
}
In another = 20
//End of another
} After another = 20
Primitives as Method Parameters
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.
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
Key Takeaways
A 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.
Quiz
QUIZ
Wrapping up of class-level variables with methods is called:
1
a. Wrapping
b. Abstraction
c. Encapsulation
d. Inheritance
QUIZ
Wrapping up of class-level variables with methods is called:
1
a. Wrapping
b. Abstraction
c. Encapsulation
d. Inheritance
The correct answer is c. Encapsulation
We tightly couple the instance variables with the methods by making the instance variables private
and generating appropriate “getters” and “setters” for them. This is known as encapsulation.
QUIZ
Which keyword should be used to access the method without creating object?
2
a. this
b. super
c. static
d. abstract
QUIZ
Which keyword should be used to access the method without creating object?
2
a. this
b. super
c. static
d. abstract
The correct answer is c. static
static objects can be accessed directly without creating an object as they are already loaded in the
memory for execution.
Thank You