KEMBAR78
Module 1 | PDF | Java Virtual Machine | Programming
0% found this document useful (0 votes)
9 views41 pages

Module 1

module 1

Uploaded by

sajin.sha2020
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)
9 views41 pages

Module 1

module 1

Uploaded by

sajin.sha2020
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/ 41

PBCST304 OBJECT ORIENTED PROGRAMMING

Module 1
I:Introduction to Java: Structure of a simple java program; Java programming Environment
and Runtime Environment (Command Line & IDE); Java compiler; Java Virtual Machine;
Primitive Data types and Wrapper Types; Casting and Autoboxing; Arrays; Strings; Vector
class; Operators - Arithmetic, Bitwise, Relational, Boolean Logical, Assignment, Conditional
(Ternary); Operator Precedence; Control Statements - Selection Statements, Iteration
Statements and Jump Statements; Functions; Command Line Arguments; Variable Length
Arguments;
II:OOP Concepts :- Data abstraction, encapsulation, inheritance, polymorphism, Procedural
and object oriented programming paradigm; Microservices.

III:Object Oriented Programming in Java :- Declaring Objects; Object Reference; Introduction


to Methods; Constructors; Access Modifiers; this keyword.

I: INTRODUCTION TO JAVA

● Java is a high level, Object Oriented and Secure programming language.


● It's not a purely object-oriented programming language because of its primitive data
type.

● Java is a popular programming language, created in 1995


● It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
● Mobile applications (especially Android apps)
● Desktop applications
● Web applications
● Smart Card
● Robotics
● Games

Types of Java Applications


There are mainly 4 types of applications that can be created using Java programming:
● Standalone Application/Desktop Applications/Window-based Applications
● Web Application
● Enterprise Application
● Mobile Application
1.Standalone Application
It is also known as desktop application or window-based applications. These are traditional
software that are needed to install on every machine.

1
PBCST304 OBJECT ORIENTED PROGRAMMING

E.g.: Media player, word etc.


2.Web Application
An application that runs on the server side and creates a dynamic page is called web
applications. Currently Servlet, JSP, Spring, hibernate etc. technologies are used for creating
web applications in java.
3.Enterprise Application
An application that is distributed in nature, Such as a banking application. It has advantages
of high-level security, Load balancing and Clustering.
4.Mobile Application
An application which is created for mobile devices is called a mobile application.
Currently Android and Java ME are used for creating mobile applications

Java Platforms / Editions


● Java SE (Java Standard Edition)
● Java EE (Java Enterprise Edition)
● Java ME (Java Micro Edition)
● JavaFX

Why Use Java?

● Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
● It is one of the most popular programming language in the world
● It is easy to learn and simple to use
● It is open-source and free
● It is secure, fast and powerful
● Java is an object oriented language which gives a clear structure to programs and allows
code to be reused.
● Reduce the development costs.
● As Java is close to languages like C++ and C#

Features of Java
Features of java is also known as Java buzzwords
1) Simple
● Java syntax is based on C++ (so it is easier for programmers to learn it after C++).
● Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
● There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

2
PBCST304 OBJECT ORIENTED PROGRAMMING

2)Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organise our software as a combination of different types of objects that
incorporate both data and behaviour.

3) Platform Independent
Java is a write once, run anywhere language.
4)Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java programs runs on JRE(Java Runtime Environment) and no interaction with our system
OS
5)Robust
Meaning of Robust is strong. Java is robust because:
● Strong memory management.
● Lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
● Exception handling and the type checking mechanism in Java.

6)Architecture-neutral
● Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
7)Portable
● Java is portable because it facilitates you to carry the Java byte code to any platform. It
doesn't require any implementation.
8)High-performance
● Java is faster than other traditional interpreted programming languages because Java
byte code is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++).
● Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
9)Distributed
● Java is distributed because it facilitates users to create distributed applications in Java.
● RMI and `EJB are used for creating distributed applications. Compared to other
languages it is easy to create network connections in Java.

3
PBCST304 OBJECT ORIENTED PROGRAMMING

10)Multi-threaded
● A thread is like a separate program, executing concurrently.
● Write Java programs that deal with many tasks at once by defining multiple threads.
● The main advantage of multi-threading is that it doesn't occupy memory for each thread.
It shares a common memory area.
● Threads are important for multimedia, Web applications, etc.

11)Dynamic
● Java is a dynamic language.
● · It supports the dynamic loading of classes.
● It means classes are loaded on demand.

Basic Structure of a Java Program.

Documentation Section
 You can write a comment in this section. It helps to understand the code. These are
optional
 It is used to improve the readability of the program.
 The compiler ignores these comments during the time of execution
 There are three types of comments that Java supports
1. Single line Comment //This is single line comment 
4
PBCST304 OBJECT ORIENTED PROGRAMMING

2. Multi-line Comment /* this is multiline comment. and support multiple lines*/


3. Documentation Comment /** this is documentation cmnt*/

Package Statement

 We can create a package with any name.


 A package is a group of classes that are defined by a name.
 That is, if you want to declare many classes within one element, then you can declare
it within a package
 It is an optional part of the program, i.e., if you do not want to declare any package,
then there will be no problem with it, and you will not get any errors.
 Package is declared as: package package_name; Eg: package mypackage;

Import Statement

 If you want to use a class of another package, then you can do this by importing it
directly into your program.
 Many predefined classes are stored in packages in Java
 We can import a specific class or classes in an import statement.
 Examples:
import java.util.Date; //imports the date class
import java.applet.*; /*imports all the classes from the java applet package*/

Interface Statement

 This section is used to specify an interface in Java


 Interfaces are like a class that includes a group of method declarations
 It's an optional section and can be used when programmers want to implement multiple
inheritances within a program.

Class Definition

 A Java program may contain several class definitions.


 Classes are the main and essential elements of any Java program.
 A class is a collection of variables and methods

Main Method Class

 The main method is from where the execution actually starts and follows the order
specified for the following statements
 Every Java stand-alone program requires the main method as the starting point of the
program. This is an essential part of a Java program.
 There may be many classes in a Java program, and only one class defines the main
method Methods contain data type declaration and executable statements.

5
PBCST304 OBJECT ORIENTED PROGRAMMING

Example
A simple java program to print hello world
public class Hello
{ //main method declaration
public static void main(String[] args)
{
System.out.println("hello world");
}
}

public class Hello –


 This creates a class called Hello.
 We should make sure that the class name starts with a capital letter, and the public word
means it is accessible from any other classes.
 Braces - The curly brackets are used to group all the commands together
 public static void main • When the main method is declared public, it means that it
can be used outside of this class as well.
 The word static means that we want to access a method without making its objects
 The word void indicates that it does not return any value. The mainis declared as void
because it does not return any value. •
 main is a method; this is a starting point of a Java program.

String[] args

 It is an array where each element is a string, which is named as args.


 If you run the Java code through a console, you can pass the input parameter.
 The main() takes it as an input.

System.out.println();

 This statement is used to print text on the screen as output


 system is a predefined class, and out is an object of the PrintWriterclass defined in the
system The method println prints the text on the screen with a new line. • We can also
use print() method instead of println() method.
 All Java statement ends with a semicolon.
Java Compiler

Source File

File name: Hello.java


public class Hello {

public static void main(String[] args) {


System.out.print("My first program in java");

6
PBCST304 OBJECT ORIENTED PROGRAMMING

Internal working during compile time

● When you compile the Hello.java file then the compiler creates a .class file
● .class file is created with the name Hello.class
● Hello.class contains byte codes

Byte code (.class file) is a specialised set of instructions that JVM can read. Thus this .class
file consisting of byte code can be transported to another system, irrespective of the operating
system it has, and could be executed comfortably without any issue.
● This is why Java is a portable language.
● Because of the same reason java is also popularly known as Write once, run anywhere
(WORA) language.
● JVM is capable of reading, verifying the bytecode.
Internal working during run time
During run or execution time following tasks are performed within JVM:
● Class loader loads the .class files containing bytecode to the memory.
● Next the bytecode is verified and checked for any errors or bugs which may result in
the program exhibiting anomalous behaviour.
● At last, the just-in-time compiler converts the bytecode into machine code.

7
PBCST304 OBJECT ORIENTED PROGRAMMING

Compile + Run diagram of java code

JVM,JRE,JDK
JAVA VIRTUAL MACHINE

JVM is a virtual machine which is capable of reading the .class file that contains bytecode.

In java, the compiler produces bytecode during compilation which can be run on any system
that has JVM installed on it. This results in making java a portable programming language. It
can be written on any system and run-on different systems easily irrespective of the operating
system. Thus, java is also referred to as write once, run anywhere.

8
PBCST304 OBJECT ORIENTED PROGRAMMING

JVM performs three major tasks:


● Loads code
● Verifies code
● Executes code
● Provides runtime environment

Java Runtime Environment - JRE

● JRE provides an environment to run java applications.


● JRE contains supporting libraries, core classes and other components that JVM uses
during the runtime.
● JRE is part of JDK. It can also be downloaded separately to just run java applications
and applets.
Main tasks performed by JVM:
▪ Loads Code
▪ Verifies Code
▪ Executes Code
▪ Provide run time environment

Java Development Kit – JDK

JDK comprises JRE and other tools that help in developing, debugging & monitoring the java
application.

A JDK always comprises of:


● JRE
● Compiler (javac)
● Debugger

9
PBCST304 OBJECT ORIENTED PROGRAMMING

● Java document

● The Java Development Kit (JDK) is a software development environment which is used
to develop Java applications and applets.
● It contains JRE + development tools.
● It physically exists.
● The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.

JAVA COMPILER
Java is compiled language. But it is very different from traditional compiling in the way that
after compilation source code isconverted to byte code. •Javac is the most popular Java
compiler • Java has a virtual machine called JVM which then converts bytecode to target code
of machine on which it is run. • JVM performs like an interpreter. It doesn’t do it alone, though.
Ithas its own compiler to convert the byte code to machine code. This compiler is called Just
In Time or JIT compiler.
JAVA APPLET
An applet is a special kind of Java program that is designed to betransmitted over the Internet
and automatically executed by aJava-compatible web browser • It runs inside the web browser
and works at client side • Applets are used to make the web site more dynamic andentertaining
• Applets are not stand-alone programs. Instead, they run withineither a web browser or an
applet viewer. JDK provides astandard applet viewer tool called applet viewer. • In general,
execution of an applet does not begin at main()method.

PRIMITIVE AND WRAPPER TYPE


Primitive and Wrapper Data Types in Java
In Java, there are two main categories of data types: primitive data types and wrapper data
types. Understanding the differences between these two is crucial for Java programming.

10
PBCST304 OBJECT ORIENTED PROGRAMMING

Primitive Data Types


Primitive data types are the most fundamental data types in Java. They are predefined by the
Java language and represent basic values such as numbers, characters, and boolean values. Java
has eight primitive data types:
1. byte: Stores an 8-bit signed integer value, ranging from -128 to 127.
2. short: Stores a 16-bit signed integer value, ranging from -32,768 to 32,767.
3. int: Stores a 32-bit signed integer value, ranging from -2,147,483,648 to 2,147,483,647.
4. long: Stores a 64-bit signed integer value, ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
5. float: Stores a 32-bit floating-point number, with a range of approximately 1.4E-45 to
3.4028235E+38.
6. double: Stores a 64-bit floating-point number, with a range of approximately 4.9E-324
to 1.7976931348623157E+308.
7. char: Stores a single 16-bit Unicode character, with a range of 0 to 65,535.
8. boolean: Stores a single bit of information, either true or false.
9. Primitive data types are directly stored in the computer's memory, and they are the most
efficient way to represent data in Java. They are also immutable, meaning their values
cannot be changed once they are assigned.
Wrapper Data Types

Wrapper data types are class representations of primitive data types. For each primitive data
type, there is a corresponding wrapper class:

1. Byte: Wrapper class for the byte primitive data type.

2. Short: Wrapper class for the short primitive data type.

3. Integer: Wrapper class for the int primitive data type.

4. Long: Wrapper class for the long primitive data type.

5. Float: Wrapper class for the float primitive data type.

6. Double: Wrapper class for the double primitive data type.

7. Character: Wrapper class for the char primitive data type.

8. Boolean: Wrapper class for the boolean primitive data type.

Wrapper classes provide additional functionality and methods that are not available in the
primitive data types. For example, they allow you to perform operations such as parsing,
formatting, and converting values. Wrapper classes are also used when you need to work with
collections, such as ArrayList or HashMap, as these collections can only store objects, not
primitive data types.

Variables In JAVA

11
PBCST304 OBJECT ORIENTED PROGRAMMING

• Variable in Java is a data container that stores the data values during Java program execution.

• Variable is a memory location name of the data.

• variable="vary + able" that means its value can be changed.

• In order to use a variable in a program we need to perform 2 steps

1. Variable Declaration

2. Variable Initialization

1. Variable Declaration

Syntax: data_type variable_name ;

Eg: int a,b,c;

float pi;

double d;

2. Variable Initialization

Syntax : data_type variable_name = value;

Eg: int a=2,b=4,c=6; int num = 45.66;

float pi = 3.14f;

double val = 20.22d;

char a = ’v’;

12
PBCST304 OBJECT ORIENTED PROGRAMMING

Types of variables

1. Local variables - declared inside the method.

2. Instance Variable - declared inside the class but outside the

method.

3. Static variable - declared as with static keyword.

OPERATORS

An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation.
Java operators can be divided into following categories:

• Arithmetic Operators

• Relational Operators

• Bitwise Operators

• Logical Operators

• Assignment Operators

• conditional operator (Ternary)

Arithmatic Operation

13
PBCST304 OBJECT ORIENTED PROGRAMMING

Relational Operators

14
PBCST304 OBJECT ORIENTED PROGRAMMING

Bitwise Operator

15
PBCST304 OBJECT ORIENTED PROGRAMMING

Logical Operators

Assignment Operators

16
PBCST304 OBJECT ORIENTED PROGRAMMING

conditional Operator / Ternary Operator ( ? : )

Expression1 ? Expression2 : Expression3

Expression ? value if true : value if false

OPERATOR PRECEDENCE
•Evaluate 2*x-3*y ?

(2x)-(3y) or 2(x-3y) which one is correct??????


• Evaluate A / B * C

17
PBCST304 OBJECT ORIENTED PROGRAMMING

A / (B * C) or (A / B) * C Which one is correct?????

To answer these questions satisfactorily one has to understand the priority or precedence of
operations.

Prepared

Precedence order - When two operators share an operand the operator with the higher
precedence goes first.
• Associativity - When an expression has two operators with the same precedence, the
expression is evaluated according to its associativity.

Larger number means higher precedence

Evaluate i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8

i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *

i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /

i = 1 + 1+ 8 - 2 + 0 operation: /
i = 2 + 8- 2 + 0 operation: +

18
PBCST304 OBJECT ORIENTED PROGRAMMING

i = 10 - 2 + 0 operation: +

i = 8 + 0 operation : -

i = 8 operation: +

SELECTION STATEMENTS

 Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
 Also called decision making statements
 Java supports various selection statements, like if, if-else and switch

There are various types of if statement in java.

 if statement
 if-else statement
 nested if statement
 if-else-if ladder
 If statement

Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}

if-else Statement
if-else statement also tests the condition. It executes the if block
if condition is true otherwise else block is executed.

Syntax
19
PBCST304 OBJECT ORIENTED PROGRAMMING

if (condition)

// block of code to be executed if the condition is true

}
else

// block of code to be executed if the condition is false

Nested if else Statement

20
PBCST304 OBJECT ORIENTED PROGRAMMING

Example

if else if ladder
Syntax
if (condition)

21
PBCST304 OBJECT ORIENTED PROGRAMMING

// block of code to be executed if the condition is true

else if (condition)
{

// block of code to be executed if the condition is true

else

// block of code to be executed if the condition is true

switch case
The if statement in java, makes selections based on a single true or false condition. But switch
case have multiple choice for selection of the statements
It is like if-else-if ladder statement

How to Java switch works:

• Matching each expression with case Once it match, execute all case from where it matched.

• Use break to exit from switch

• Use default when expression does not match with any case

Syntax

22
PBCST304 OBJECT ORIENTED PROGRAMMING

Why break is necessary in switch statement ?


• The break statement is used inside the switch to terminate a statement sequence.

• When a break statement is encountered, execution branches to the first line of code that
follows the entire switch statement

• This has the effect of jumping out of the switch.

• The break statement is optional. If you omit the break, execution will continue on into the
next case.

Iteration Statements (Loop)


• A loop can be used to tell a program to execute statements repeatedly

• A loop repeatedly executes the same set of instructions until a termination condition is met.

23
PBCST304 OBJECT ORIENTED PROGRAMMING

While Loop
In while loop first checks the condition if the condition is true then control goes inside the loop
body otherwise goes outside of the body.

Syntax

while (condition)

// code block to be executed

do...while loop
A do while loop is a control flow statement that executes a block of code at least once, and
then repeatedly executes the block, or not, depending on a given condition at the end of the
block (in while).

Syntax

do {
// code block to be executed

24
PBCST304 OBJECT ORIENTED PROGRAMMING

} while (condition);

for loop
For Loop is used to execute set of statements repeatedly until the condition is true.

Syntax

for (initialization; condition; increment/decrement)

// code block to be executed

Initialization : It executes at once.

Condition : This check until get true.

Increment/Decrement: This is for increment or decrement.

25
PBCST304 OBJECT ORIENTED PROGRAMMING

Jump statements
Java Break Statement

 The Java break statement is used to break loop or switch statement


 It breaks the current flow of the program at specified condition
 When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
 In case of inner loop, it breaks only inner loop.

Java Continue Statement

 The Java continue statement is used to continue the loop The continue statement is used
in loop control structure when you need to jump to the next iteration of the loop
immediately

26
PBCST304 OBJECT ORIENTED PROGRAMMING

 It continues the current flow of the program and skips the remaining code at the
specified condition.
 In case of an inner loop, it continues the inner loop only.

ARRAY
• An array is a collection of similar data types.

• Java array is an object which contains elements of a similar data type.


• The elements of an array are stored in a contiguous memory location The size of an array is
fixed and cannot increase to accommodate more elements

• It is also known as static data structure because size of an array must be specified at the time
of its declaration.

• Array in Java is index-based, the first element of the array is stored at the 0th index
Java provides the feature of anonymous arrays which is not available in C/C++.

Advantage of Java Array


• Code Optimization: It makes the code optimized, we can retrieve or

sort the data easily.

• Random access: We can get any data located at any index position.

Disadvantage of Java Array


• Size Limit: We can store the only fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in java.

Features of Array

27
PBCST304 OBJECT ORIENTED PROGRAMMING

• It is always indexed. The index begins from 0.

• It is a collection of similar data types.

• It occupies a contiguous memory location.

Types of Java Array


• Single Dimensional Array

• Multidimensional Array

Single Dimensional Array in java

Array Declaration
Syntax: datatype[ ] arrayname;

Eg: int[ ] arr;

char[ ] name;
short[ ] arr;

long[ ] arr;

int[ ][ ] arr; //two dimensional array

In C program datatype arrayname[];

Initialization of Array
new operator is used to initializing an array.

Eg 1: int[ ] arr = new int[10];


or

int[ ] arr = {10,20,30,40,50};

Eg 2: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Eg 3: double[] myList = new double[10];

Two Dimensional array

Array Declaration

 Syntax : datatype[ ][ ] arrayname;


 Eg: int[][] myNumbers ;
 Array Initialization
 int[ ][ ] arrName = new int[10][10];
 Or
 int[ ][ ] arrName = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}}; // 3 by

28
PBCST304 OBJECT ORIENTED PROGRAMMING

5 is the size of the array.

STRING
 Strings are used for storing text
 A String variable contains a collection of characters surrounded by double quotes
 Eg: Create a variable of type String and assign it a value
 String greeting = "Hello";

Output
Hello

 In Java, string is basically an object that represents sequence of char values


 An array of characters works same as Java string. For example:
 char[] ch={'j',‘o',‘s',‘e',‘p',‘h'};
 String s=new String(ch); //converting char array to string is same as
 String s="joseph"; //creating string by java string literal

String Length
• The length of a string can be found with the length() method

toUpperCase() and toLowerCase()

29
PBCST304 OBJECT ORIENTED PROGRAMMING

Output

HELLO WORLD

hello world

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a specified text
in a string (including whitespace)

Output 7

String Concatenation
• The + operator can be used between strings to combine them. This is called concatenation

Output John Doe

concat() method

30
PBCST304 OBJECT ORIENTED PROGRAMMING

• We can also use the concat() method to concatenate two strings:

Adding Numbers and Strings


• Java uses the + operator for both addition and concatenation.
• If we add two strings, the result will be a string concatenation

Command-Line Arguments
• Sometimes we want to pass information into a program when we run it. This is accomplished
by passing command-line arguments to main( ).

• The main method can receive string arguments from the command line
• To access the command-line arguments inside a Java program is quite easy— they are stored
as strings in a String array passed to the args parameter of main( ).

• The first command-line argument is stored at args[0], the second at args[1], and so on.

31
PBCST304 OBJECT ORIENTED PROGRAMMING

II: BASIC OBJECT ORIENTED PROGRASMMING (OOPS)CONCEPTS


Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some concepts:

1)Object

● Any entity that has state and behaviour is known as an object. It can be physical or logical.

● An Object can be defined as an instance of a class.

● An object contains an address and takes up some space in memory.

● Example: A dog is an object because it has states like colour, name, breed, etc. as well as
behaviours like wagging the tail, barking, eating, etc.
● A dog is an object because it has states like colour, name, breed, etc. as well as behaviours
like wagging the tail, barking, eating, etc.
32
PBCST304 OBJECT ORIENTED PROGRAMMING

2)Class
● Collection of objects is called class. It is a logical entity.

● A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.

3)Inheritance
Inheritance is a mechanism in which one class acquires the property of another class.

With inheritance, we can reuse the fields and methods of the existing class.

Hence, inheritance facilitates Reusability and is an important concept of OOPs.

● As we know, a child inherits the properties from his parents. A similar concept is followed in
Java, where we have two classes:

● Parent class (Super or Base class)

● Child class (Subclass or Derived class)

● A class which inherits the properties is known as Child Class whereas a class whose
properties are inherited is known as Parent class

Inheritance Syntax:
class Subclass extends superClass

//methods and fields


}

4)Encapsulation
● Encapsulation is a process of wrapping code and data together into a single unit, for example,
a capsule which is mixed of several medicines.

● In encapsulation, a class's variables are hidden from other classes and can only be accessed
by the methods of the class in which they are found

● 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.

The Java Bean class is the example of a fully encapsulated class.

33
PBCST304 OBJECT ORIENTED PROGRAMMING

Syntax:

<Access_Modifier> class <Class_Name>

private <Data_Members>;
private <Data_Methods>;

Need for Encapsulation


· Better Control

· Setter and Getter

· Security

Flexibility

5)Polymorphism
Polymorphism 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.

Two types of polymorphism

● Compile-time polymorphism

● Runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.

Runtime Polymorphism (Dynamic Polymorphism)

● 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.
Compile time Polymorphism(or Static Polymorphism)

● Polymorphism that is resolved during compiler time is known as static

polymorphism.

● Method overloading is an example of compile time polymorphism

III)OBJECT ORIENTED PROGRAMMING IN JAVA

What is a class?
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
34
PBCST304 OBJECT ORIENTED PROGRAMMING

A class in Java can contain:


● Fields
● Methods
● Constructors
● Blocks
● Nested class and interface

Syntax to declare a class:

class <class name>

field;

method;

What is an object?

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

How to create an object?(Declaring object)

Syntax:
ClassName object = new Constructor();

Using new Keyword(object reference)

35
PBCST304 OBJECT ORIENTED PROGRAMMING

Using the new keyword is the most popular way to create an object or instance of the class.
When we create an instance of the class by using the new keyword, it allocates memory (heap)
for the newly created object and also returns the reference of that object to that memory

Constructors
Constructor is a block of codes similar to the method. It is called when an instance of the class
is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new () keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

Rules for creating Java constructor


There are two rules defined for the constructor.
● Constructor name must be the same as its class name
● A Constructor must have no explicit return type
● A Java constructor cannot be abstract, static, final, and synchronised
Types of Java constructors
There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

Default Constructor
A constructor is called a "Default Constructor" when it doesn't have any parameter.

Purpose:
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

Syntax:
class name(){}

Example
class Fruit

//creating a default constructor

Fruit ()

36
PBCST304 OBJECT ORIENTED PROGRAMMING

System.out.println("Fruit is created");

//main method

public static void main(String args[])

//calling a default constructor

Fruit f = new Fruit ();

Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Purpose:

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example

class Fruit

//creating a parameterized constructor

Fruit (String str)

System.out.println("Fruit is created as" +str);

//main method

37
PBCST304 OBJECT ORIENTED PROGRAMMING

public static void main(String args[])

//calling a parameterized constructor

Fruit f=new Fruit(“Apple”);

Access Modifiers

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specify the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of access modifiers:

● Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
● Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
● Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
● Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronised, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

38
PBCST304 OBJECT ORIENTED PROGRAMMING

Access within within outside package outside


Modifier class package by subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Keyword

this keyword
● this is a reference variable that refers to the current object.

Uses of ‘this’ keyword

 It can be used to refer instance variable of current class


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

39
PBCST304 OBJECT ORIENTED PROGRAMMING

public class Example {

int value;

public Example(int value) {


this.value = value; // 'this.value' refers to the instance variable

// 'value' refers to the parameter

Invoking current class methods: this.methodName() can be used to explicitly call another
method within the same class. While often optional, it enhances clarity

public class MyClass {


public void methodA() {

// ...

public void methodB() {

this.methodA(); // Invokes methodA of the current object

Invoking current class constructors (Constructor Chaining): this() or this(arguments) can


be used within a constructor to call another constructor of the same class. This facilitates code
reuse and ensures consistent object initialization. This call must be the first statement in the
constructor.
public class Rectangle {

int x, y, width, height;

public Rectangle() {

this(0, 0, 1, 1); // Calls the four-argument constructor


}

40
PBCST304 OBJECT ORIENTED PROGRAMMING

public Rectangle(int x, int y, int width, int height) {

this.x = x;

this.y = y;

this.width = width;
this.height = height;

41

You might also like