Quick introduction to Object oriented concepts in Java - Part 2 of series
Chapters
What is Encapsulation?
Encapsulation is method of packing data and functions into single component. Encapsulation in Java or object oriented programming language will enforce protection of variables, functions from outside class, which will help in better manage piece of code and have least impact or no impact on other part of program due to change in any part of protected code. With the use of Private keyword complete encapsulation of variable or method can be achieved, for lesser encapsulation we can use protected or public keyword.
Java provides three keywords in order to define scope and access permissions of a class method or member: public, private and protected.
A public method or member is accessed from any other class.
A private method or member is accessed within own class.
A protected method or member is accessed within own class, sub-classes and in all classes within same package.
Here is an example code
public class Student { private String name; // accessible within class private int age; public intgetAge() { // accessible outside the class return age; } public String getName() { return name; } public void setAge(intnewAge) { age = newAge; } public void setName(String newName) { name = newName; } } public class TestEncap { public static void main(String args[]) { Student st = new Student(); st.setName("Jane"); st.setAge(18);
// st.age; will produce a compile time error. System.out.print("Name : " + st.getName() + " Age : " + st.getAge()); } }
Output:
Name: Jane Age: 18
Advantage of Encapsulation:
- It is flexible and easy to change with new requirements.
- It allows controlling who can access what.
- It allows changing part of protected code without affecting other part of code.
Description
This tutorial will introduce you to Object oriented concepts in Java. Basic definitions and learning with code examples.
This tutorial has subdivided into 7 parts as listed below
- Understanding Inheritance
- Understanding Overrides
- Understanding Polymorphism
- Understanding Abstraction
- Understanding Encapsulation
- Understanding Interfaces
- Understanding Packages
Let us know if you found any error in this tutorial. Your feedback is welcome as always.
Audience
Students seeking a quick overview on Java Programming language and its Object oriented features.
Learning Objectives
Learn Object Oriented concepts in Java language.
Author: Subject Coach
Added on: 10th Mar 2015
You must be logged in as Student to ask a Question.
None just yet!