Docsity

Advance OOP using Java, Lecture notes of Java Programming

Partial preview of the text

Download Advance OOP using Java and more Lecture notes Java Programming in PDF only on Docsity!

Advanced

OOP using

JAVA

Content Created by Imtiaz Saifullah +92-331-

OOP Concepts in Java

Contoso

OOP Concepts in

Java

Java is a class-based object-oriented programming (OOP) language that is built around the

concept of objects.

OOP concepts (OOP) intend to improve code readability and reusability by defining how to

structure a Java program efficiently.

The main principles of object-oriented programming are:

Abstraction Encapsulation Inheritance Polymorphism 2

Contoso

Example 1:

We will set two fields as private name and

email in class UserDetails.

So these fields can only be access within this

class and no outside class can access it.

Also here we will create public methods getter

(Ex. getName()) and setter (Ex. setName()) to

read and write data on those fields from

outside class.

By doing this we are hiding the fields and its

implementation from outside class.

This whole process is known as Encapsulation

which is also called as Data Hiding.

Encapsulation

Encapsulation is all about wrapping

variables and methods in one single

unit with the sole purpose of data

hiding from external classes.

4

Contoso

ublic class UserDetails { private String name; private String email; public String getName() { return name; } public void setName (String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 5

Step 1:

Create a class

UserDetails, two private

fields name and Email.

Also create public getter

and setter methods.

public static void main(String[] args) { UserDetails userDetails = new UserDetails(); userDetails.setName(“Saif Khan"); userDetails.setEmail("info@saifkhan. com"); System.out.println("Name:"+userDet ails.getName()); System.out.println("Email: "+userDetails.getEmail()); } } Output: Name: Saif Khan Email: [email protected]