[go: up one dir, main page]

0% found this document useful (0 votes)
14 views58 pages

Chapter 5-Oop Concepts

Chapter five covers key Object-Oriented Programming (OOP) concepts in Java, including inheritance, polymorphism, method overriding, and encapsulation. It explains how inheritance allows classes to acquire properties and behaviors from parent classes, and discusses the use of the 'super' keyword. Additionally, the chapter details method overloading and overriding, emphasizing their roles in enhancing code readability and achieving runtime polymorphism.

Uploaded by

Woldeab Bisrat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views58 pages

Chapter 5-Oop Concepts

Chapter five covers key Object-Oriented Programming (OOP) concepts in Java, including inheritance, polymorphism, method overriding, and encapsulation. It explains how inheritance allows classes to acquire properties and behaviors from parent classes, and discusses the use of the 'super' keyword. Additionally, the chapter details method overloading and overriding, emphasizing their roles in enhancing code readability and achieving runtime polymorphism.

Uploaded by

Woldeab Bisrat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Object oriented Programming

Chapter five :
OOP concepts
Outline

 Inheritance
 Super
 Polymorphism
 Method Overriding and Overloading
 The Object Class
 Abstract Classes
 Interfaces
 Encapsulation
Inheritance in Java

 Inheritance in Java is a mechanism in which one object


acquires all the properties and behaviors of a parent
object.
 The idea behind inheritance in Java is that you can
create new classes that are built upon existing classes.
 When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you
can add new methods and fields in your current class
also.
 Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.
Terms used in Inheritance

 Class: A class is a group of objects which have common


properties. It is a template or blueprint from which objects are
created.
 Sub Class/Child Class: Subclass is a class which inherits the
other class. It is also called a derived class, extended class, or
child class.
 Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a base
class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the
 Why use inheritance in java
– For Method Overriding (so runtime polymorphism can
be achieved).
– For Code Reusability.
 The syntax of Java Inheritance
class Subclass-name extends Superclass-name {
//methods and fields
}
 The extends keyword indicates that you are making a
new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
Java Inheritance Example

• As displayed in the above figure,


Programmer is the subclass and
Employee is the superclass.
• The relationship between the two
classes is Programmer IS-A
Employee. It means that
Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
 In the above example, Programmer object can access the field of own
class as well as of Employee class i.e. code reusability.
Types of inheritance in java

 On the basis of class, there can be three types of


inheritance in java: single, multilevel and hierarchical.
 In java programming, multiple and hybrid inheritance is
supported through interface only. We will learn about
interfaces later.
Types of inheritance in java.

 On the basis of class, there can be three types of


inheritance in java: single, multilevel and hierarchical
Example2.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
Output
d.eat(); barking...
}} eating...
Super Keyword in Java

 The super keyword in Java is a reference variable which


is used to refer immediate parent class object.
 Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
 Usage of Java super Keyword
– super can be used to refer immediate parent class instance
variable.
– super can be used to invoke immediate parent class method.
– super() can be used to invoke immediate parent class constructor.
1.class Animal{
1. We can use 2.String color="white";
super keyword to 3.}
4.class Dog extends Animal{
access the data 5.String color="black";
member or field 6.void printColor(){
7.System.out.println(color);//prints color of Dog class
of parent class. It 8.System.out.println(super.color);//prints color of Animal
is used if parent class
9.}
class and child 10.}
class have same 11.class TestSuper1{
12.public static void main(String args[]){
fields. 13.Dog d=new Dog();
Output 14.d.printColor();
15.}}
black
white
2) super can be used to invoke parent class method

1.class Animal{
 The super keyword 2.void eat(){System.out.println("eating...");}
can also be used to 3.}
4.class Dog extends Animal{
invoke parent class 5.void eat(){System.out.println("eating bread...");}
method. It should be 6.void bark(){System.out.println("barking...");}
7.void work(){
used if subclass 8.super.eat();
contains the same 9.bark();
10.}
method as parent 11.}
class. In other words, 12.class TestSuper2{
13.public static void main(String args[]){
it is used if method is 14.Dog d=new Dog();
overridden. 15.d.work();
Output 16.}}
eating...
barking...
3) super is used to invoke parent class constructor.

 The super 1.class Animal{


2.Animal(){System.out.println("animal is created");}
keyword can 3.}
also be used to 4.class Dog extends Animal{
5.Dog(){
invoke the 6.super();
parent class 7.System.out.println("dog is created");
8.}
constructor. 9.}
Let's see a 10.class TestSuper3{
11.public static void main(String args[]){
simple example: 12.Dog d=new Dog();
13.}}
Output
animal is created
dog is created
super example: real use

1. class Person{
2. int id; 1.void display(){System.out.println(id+" "+
3. String name; name+" "+salary);}
4. Person(int id,String name){ 2.}
3.class TestSuper5{
5. this.id=id;
4.public static void main(String[] args){
6. this.name=name; 5.Emp e1=new Emp(1,"ankit",45000f);
7. } 6.e1.display();
8. } 7.}}
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constru
ctor Output
13. this.salary=salary; 1 ankit 45000
14. }
Polymorphism in Java

 Polymorphism in Java is a concept by which we can


perform a single action in different ways. Polymorphism
is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms.
So polymorphism means many forms.
 There are two types of polymorphism in Java: compile-
time polymorphism and runtime polymorphism. We can
perform polymorphism in java by method overloading
and method overriding.
 If you overload a static method in Java, it is the example
of compile time polymorphism. Here, we will focus on
Runtime Polymorphism in Java

 Runtime polymorphism or Dynamic Method Dispatch is a


process in which a call to an overridden method is resolved at
runtime rather than compile-time.
 In this process, an overridden method is called through the
reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by
the reference variable.
 Upcasting: If the reference variable of Parent class refers to
the object of Child class, it is known as upcasting. For example:
1. class A{}
2. class B extends A{}
3. A a=new B();//upcasting
 Example of Java Runtime Polymorphism: Consider a scenario
where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to
banks. For example, SBI, ICICI, and AXIS banks are providing
8.4%, 7.3%, and 9.7% rate of interest
1. class Bank{
2. float getRateOfInterest(){return 0;} 13. class TestPolymorphism{
3. } 14. public static void main(String args[]){
4. class SBI extends Bank{ 15. Bank b;
5. float getRateOfInterest(){return 8.4f;} 16. b=new SBI();
6. } 17. System.out.println("SBI Rate of Interest:
"+b.getRateOfInterest());
7. class ICICI extends Bank{
18. b=new ICICI();
8. float getRateOfInterest(){return 7.3f;}
19. System.out.println("ICICI Rate of Interes
9. }
t: "+b.getRateOfInterest());
10. class AXIS extends Bank{
20. b=new AXIS();
11. float getRateOfInterest(){return 9.7f;}
21. System.out.println("AXIS Rate of Interes
12. } t: "+b.getRateOfInterest());
Output 22. }
SBI Rate of Interest: 8.4 23. }
ICICI Rate of Interest: 7.3
Java Runtime Polymorphism Example: Shape

1. class Shape{
2. void draw(){System.out.println("drawing...");}
3. }
4. class Rectangle extends Shape{
5. void draw(){System.out.println("drawing rectangle...");}
6. }
7. class Circle extends Shape{
8. void draw(){System.out.println("drawing circle...");}
9. }
10. class Triangle extends Shape{
11. void draw(){System.out.println("drawing triangle...");}
12. }
13. class TestPolymorphism2{
//example3
14. public static void main(String args[]){ 1.class Animal{
2.void eat(){System.out.println("eating...");}
3.}
15. Shape s; 4.class Dog extends Animal{
5.void eat(){System.out.println("eating bread...");}
16. s=new Rectangle(); 6.}
7.class Cat extends Animal{
17. s.draw(); 8.void eat(){System.out.println("eating rat...");}
9.}
10.class Lion extends Animal{
18. s=new Circle(); 11.void eat(){System.out.println("eating meat...");}

19. s.draw(); 12.}


13.class TestPolymorphism3{
20. s=new Triangle(); 14.public static void main(String[] args){
15.Animal a;
21. s.draw(); 16.a=new Dog();
17.a.eat();
18.a=new Cat();
22. } Output 19.a.eat();
20.a=new Lion();
23. } drawing rectangle... 21.a.eat();
drawing circle... 22.}}

drawing triangle...
Method Overloading and Overriding

 If a class has multiple methods having same name but


different in parameters, it is known as Method Overloading.
 If we have to perform only one operation, having same name
of the methods increases the readability of the program.
 Suppose you have to perform addition of the given numbers
but there can be any number of arguments, if you write the
method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method
because its name differs.
 So, we perform method overloading to figure out the program
quickly.
 Advantage of method overloading
– Method overloading increases the readability of the
program.
 Different ways to overload the method: There are two
ways to overload the method in java
– By changing number of arguments
– By changing the data type of the arguments
 In Java, Method Overloading is not possible by changing
the return type of the method only.
1) Method Overloading: changing no. of arguments

 In this example, we have created two methods, first add()


method performs addition of two numbers and second
add method performs addition of three numbers.
 In this example, we are creating static methods so that
we don't need to create instance for calling methods.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;} Output
4. } 22
5. class TestOverloading1{ 33
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
2) Method Overloading: changing data type of arguments

 In this example, we have created two methods that differs


in data type. The first add method receives two integer
arguments and second add method receives two double
arguments
1.class Adder{
2.static int add(int a, int b){return a+b;}
3.static double add(double a, double b){return a+b;}
Output
4.}
22
5.class TestOverloading2{
24.9
6.public static void main(String[] args){
7.System.out.println(Adder.add(11,11));
8.System.out.println(Adder.add(12.3,12.6));
9.}}
 In general in order to overload a method, the argument lists of the
methods must differ in either of these:
1. Number of parameters. For example:
add(int, int)
add(int, int, int)
2. Data type of parameters. For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters. For example:
add(int, float)
add(float, int)
 Note: if two methods have same name, same parameters and have
different return type, then this is not a valid method overloading.
Method Overriding in Java

 If subclass (child class) has the same method as declared


in the parent class, it is known as method overriding in
Java.
 In other words, If a subclass provides the specific
implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
 Usage of Java Method Overriding
– Method overriding is used to provide the specific
implementation of a method which is already provided
by its superclass.
– Method overriding is used for runtime polymorphism
 Rules for Java Method Overriding
– The method must have the same name as in the parent class
– The method must have the same parameter as in the parent class.
– There must be an IS-A relationship (inheritance).
1. //Java Program to illustrate the use of Java Method Overriding
2. class Vehicle{ //Creating a parent class.
3. void run(){System.out.println("Vehicle is running");} //defining a method
4. }
5. class Bike2 extends Vehicle{ //Creating a child class
6. //defining the same method as in the parent class
7. void run(){System.out.println("Bike is running safely");}
8. public static void main(String args[]){
9. Bike2 obj = new Bike2();//creating object
Output
10. obj.run();//calling method
Bike is running safely
11. }
12. }
Example2 real example

1. //Java Program to demonstrate the real Bank scenario of java method


Overriding //where three classes are overriding the method of a parent class.
2. //Creating a parent class.
3. class Bank{
4. int getRateOfInterest(){return 0;}
5. }
6. //Creating child classes.
7. class SBI extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10. class ICICI extends Bank{
11. int getRateOfInterest(){return 7;}
14. class AXIS extends Bank{
15. int getRateOfInterest(){return 9;}
16. }
17. //Test class to create objects and call the methods
18. class Test2{ Output
SBI Rate of Interest: 8
19. public static void main(String args[]){
ICICI Rate of Interest: 7
20. SBI s=new SBI(); AXIS Rate of Interest: 9
21. ICICI i=new ICICI();
22. AXIS a=new AXIS();
23. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
24. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
25. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
26. }
Overriding vs Overloading
No. Method Overloading Method Overriding
1) Method overloading is used to Method overriding is used to provide the
increase the readability of the specific implementation of the method that is
program. already provided by its super class.

2) Method overloading is performed Method overriding occurs in two classes that


within class. have IS-A (inheritance) relationship.
3) In case of method overloading In case of method overriding, parameter
,parameter must be different. must be same.
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in
performed by changing return type of method overriding.
the method only. Return type can be
same or different in method
overloading. But you must have to
change the parameter.
Difference between constructor and method ?

Constructor Method
• Constructor is used to initialize • Method is used to expose
the state of an object. behaviour of an object.
• Constructor must not have • Method must have return
return type. type.
• Constructor is invoked • Method is invoked
implicitly. explicitly.
• The java compiler provides a
• Method is not provided by
default constructor if you don't
compiler in any case.
have any constructor.
• Constructor name must be same • Method name may or may
32 as the class name. not be same as class name.
Abstraction in Java

 Abstraction is a process of hiding the implementation details


and showing only functionality to the user.
 Another way, it shows only essential things to the user and
hides the internal details, for example, sending SMS where you
type the text and send the message. You don't know the
internal processing about the message delivery.
 Abstraction lets you focus on what the object does instead of
how it does it.
 Ways to achieve Abstraction
 There are two ways to achieve abstraction in java
– Abstract class
– Interface
… Abstract class in Java

 A class which is declared as abstract is known as


an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method
implemented. It cannot be instantiated.
 Points to Remember (rules of abstract class)
– An abstract class must be declared with an abstract keyword.
– It can have abstract and non-abstract methods.
– It cannot be instantiated.
– It can have constructors and static methods also.
– It can have final methods which will force the subclass not to
change the body of the method.
 Example of abstract class
1. abstract class A{}
 Abstract Method in Java: A method which is declared as
abstract and does not have implementation is known as
an abstract method.
 Example of abstract method
1. abstract void printStatus();//no method body and abstract
Example of Abstract class that has an abstract method

 In this example, Bike is an abstract class that contains


only one abstract method run. Its implementation is
provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run(); Output
running safely
9. }
 Understanding the real scenario of Abstract class
 In this example, Shape is the abstract class, and its
implementation is provided by the Rectangle and Circle
classes
 Mostly, we don't know about the implementation class
(which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
 A factory method is a method that returns the instance of
the class..
 In this example, if you create the instance of Rectangle
class, draw() method of Rectangle class will be invoked.
//File: TestAbstraction1.java
1. abstract class Shape{
2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. } Output
11. //In real scenario, method is called by programmer or user
drawing circle
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() me
thod
15. s.draw();
Another example of Abstract class in java

1. abstract class Bank {


2. abstract int getRateOfInterest(); }
3. class SBI extends Bank{
4. int getRateOfInterest(){return 7;}
Output
5. }
Rate of Interest is: 7 %
6. class PNB extends Bank{ Rate of Interest is: 8 %
7. int getRateOfInterest(){return 8;}
8. }
9. class TestBank{
10. public static void main(String args[]){
11. Bank b;
12. b=new SBI();
13. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
14. b=new PNB();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
Abstract class having constructor, data member and
methods

 An abstract class can have a data member, abstract method, method


body (non-abstract method), constructor, and even main() method.
1.//Example of an abstract class that has abstract and no
n-abstract methods 11. //Creating a Test class which c
2. abstract class Bike{
alls abstract and non-
3. Bike(){System.out.println("bike is created");}
4. abstract void run(); abstract methods
5. void changeGear(){System.out.println("gear change 12. class TestAbstraction2{
d");} 13. public static void main(Strin
6. }
7.//Creating a Child class which inherits Abstract class
g args[]){
8. class Honda extends Bike{ 14. Bike obj = new Honda();
9. void run(){System.out.println("running safely..");} 15. obj.run();
10. }
16. obj.changeGear();
Output 17. }
bike is created 18. }
running safely..
Interface in Java

 An interface in Java is a blueprint of a class. It has


static constants and abstract methods.
 The interface in Java is a mechanism to
achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
 In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method
body.
 Java Interface also represents the IS-A relationship
 It cannot be instantiated just like the abstract class.
 Why use Java interface?
 There are mainly three reasons to use interface. They are
given below.
– It is used to achieve abstraction.
– By interface, we can support the functionality of
multiple inheritance.
– It can be used to achieve loose coupling
(independent)
 An interface is declared by using the interface keyword. It
provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the
fields are public, static and final by default. A class that
implements an interface must implement all the methods
declared in the interface.
 Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
}
The relationship between classes and interfaces

 As shown in the figure given below, a class extends another


class, an interface extends another interface, but a class
implements an interface.

 Java Interface Example: In this example, the Printable


interface has only one method, and its implementation is
provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6. public static void main(String args[]){
7. A6 obj = new A6();
Output
8. obj.print(); Hello
9. }
10. }
Java Interface Example: Drawable

 In this example, the Drawable interface has only one


method. Its implementation is provided by Rectangle and
Circle classes. In a real scenario, an interface is defined
by someone else, but its implementation is provided by
different implementation providers. Moreover, it is used
by someone else. The implementation part is hidden by
the user who uses the interface.
1. //Interface declaration: by first user
2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");} Output
11. } drawing circle
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. d.draw();
17. }}
Java Interface Example: Bank

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;} Output
9. } ROI: 9.15
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
Multiple inheritance in Java by interface

 Multiple inheritance in Java by interface


 If a class implements multiple interfaces, or an interface
extends multiple interfaces, it is known as multiple
inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
Output
9. public void show(){System.out.println("Welcome");}
Hello
10. public static void main(String args[]){
Welcome
11. A7 obj = new A7();
12. obj.print();
13. obj.show();
14. }
15. }
Encapsulation in Java

 Encapsulation in Java is a process of wrapping code and


data together into a single unit, for example, a capsule
which is mixed of several medicines.
 We can create a fully encapsulated class in Java by
making all the data members of the class private. Now
we can use setter and getter methods to set and get the
data in it.
 To achieve encapsulation in Java −
– Declare the variables of a class as private.
– Provide public setter and getter methods to modify
and view the variables values.
 Getters and setters are used to protect your data,
particularly when creating classes.
 For each instance variable, a getter method returns its
value while a setter method sets or updates its value.
 By Java convention,
 Getter methods,
– Start with ‘get’ keyword followed by the variable name with the
first letter of the variable as capitalized
– Return the attribute value
 Setter methods,
– Start with ‘set’ keyword followed by the variable name with the
 Advantage of Encapsulation in Java
– By providing only a setter or getter method, you can make the
class read-only or write-only.
– It provides you the control over the data. Suppose you want to set
the value of id which should be greater than 100 only, you can write
the logic inside the setter method. You can write the logic not to store
the negative numbers in the setter methods.
– It is a way to achieve data hiding in Java because other class will
not be able to access the data through the private data members.
– The encapsulate class is easy to test. So, it is better for unit testing.
– The standard IDE's are providing the facility to generate the getters
and setters. So, it is easy and fast to create an encapsulated
class in Java.
vijay

Simple Example of Encapsulation in Java

 Let's see the simple example of encapsulation that has


only one field with its setter and getter methods.
1. /*A Java class which is a fully encapsulated class.It has a private data member and getter and sett
er methods*/.
2. package javapoint; 14. /A Java class to test the encapsulated class.
3. public class Student{ 15. package javapoint;
4. //private data member 16. class Test{
17. public static void main(String[] args){
5. private String name;
18. //creating instance of the encapsulated class
6. //getter method for name 19. Student s=new Student();
7. public String getName(){ 20. //setting value in the name member
8. return name; 21. s.setName(“samuel");
9. } 22. //getting value of the name member
23. System.out.println(s.getName());
10. //setter method for name
24. }
11. public void setName(String name){ 25. }
12. this.name=name Output
13. } } samuel
 Read-Only class: Now, you can't change the value of
the college data member which is "AKG".
1.//A Java class which has only getter Write-Only class
methods. 1.//A Java class which has only setter m
2.public class Student{ ethods.
3.//private data member 2.public class Student{
4.private String college="AKG"; 3.//private data member
5.//getter method for college 4.private String college;
6.public String getCollege(){ 5.//getter method for college
7.return college; 6.public void setCollege(String college)
8.} {
9.} 7.this.college=college;
8.}
9.}
Another Example of Encapsulation in Java

 Let's see another example of encapsulation that has only


four fields with its setter and getter methods.
1. //A Account class which is a fully encapsulated class.
18. public void setName(String name) {
2. //It has a private data member and getter and setter methods.
19. this.name = name;
3. class Account {
20. }
4. //private data members
21. public String getEmail() {
5. private long acc_no;
22. return email;
6. private String name,email;
23. }
7. private float amount;
24. public void setEmail(String email) {
8. //public getter and setter methods
25. this.email = email;
9. public long getAcc_no() {
26. }
10. return acc_no;
27. public float getAmount() {
11. }
28. return amount;
12. public void setAcc_no(long acc_no) {
29. }
13. this.acc_no = acc_no;
30. public void setAmount(float amount)
14. }
{
15. public String getName() {
31. this.amount = amount;
16. return name;
32. }
17. }
File: TestAccount.java

1. //A Java class to test the encapsulated class Account.


2. public class TestEncapsulation {
3. public static void main(String[] args) {
4. Account acc=new Account(); //creating instance of Account class
5. acc.setAcc_no(7560504000L); //setting values through setter methods
6. acc.setName("Sonoo Jaiswal");
7. acc.setEmail("sonoojaiswal@gmail.com");
8. acc.setAmount(500000f);
9. //getting values through getter methods
10. System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.g
etAmount());
11. }
12. }
Output
7560504000 Sonoo Jaiswal sonoojaiswal@gmail.com 500000.0
 THANK YOU !

You might also like