Uploaded by Madhav kumar

OOP Fundamentals in Java: Presentation

advertisement
Module 1
Object-Oriented Programming
– Fundamentals
Dr. Rohit Kumar Das
Assistant Professor Senior Grade 2
SCOPE, VIT-AP University
Content
Features of OOP
Data types, variables, Array
 Operators
String function
Control statements
Objects and Classes in Java - Defining Classes – Methods
Access Specifiers,
Static Members,
Constructors,
this Keyword
Encapsulation
Intro: Object-Oriented Programming (OOP)
Object  entity that exists in the real world
Oriented  interested in a particular kind of thing or entity
Object-Oriented programming
 Programming that rounds around an object or entity
A computer programming design philosophy or methodology that
organizes/ models software design around data, or objects rather
than functions and logic.
Intro: Object-Oriented Programming (OOP)
 OOP is a programming paradigm that organizes code into reusable and self-contained
objects. .
 In OOP, a program is designed by creating and manipulating objects, which are
instances of classes.
 A class is a blueprint or template that defines the attributes (data members) and
behaviors (methods or functions) that the objects of the class will have
 An Object is an instance of a Class.
✓ Objects contain data and functions.
✓ Data in the form of fields (data field) that has unique attributes and behavior.
✓ Function is designed in the form of methods.
Intro: Object and Class
Intro: Object and Class
Intro: Object vs Class
Class
Object
Memory is not allocated to classes. Classes have no physical
existence.
You can declare a class only once.
Class is a logical entity.
An object is a class instance that allows programmers to use
variables and methods from inside the class.
When objects are created, memory is allocated to them in the
heap memory.
A class can be used to create many objects.
An object is a physical entity.
We cannot manipulate class as it is not available in memory.
Objects can be manipulated.
A class is a blueprint for declaring and creating objects.
Class is created using the class keyword like class Dog{}
Example: Mobile is a class.
Objects are created through new keyword like Dog d = new
Dog();. We can also create an object using the newInstance()
method, clone() method, fatory method and using
deserialization.
If Mobile is the class then iphone, redmi, blackberry,
samsung are its objects which have different properties and
behaviours.
Classes can have attributes and methods defined.
Objects can have specific values assigned to their attributes.
Classes serve as blueprints for creating objects.
Objects represent specific instances created from a class.
Data Types in Java
 Data types in Java are of different sizes and values that can be stored in the variable.
 Data Types mean to identify the type of data and associate operations that can be done
on the data values.
 Data types also tell us information about:
 The size of the memory location.
 The maximum and minimum value of the range that can store in the memory location.
 Different types of operations can be done on the memory location
Primitive Data Types
 Data types that are predefined in
the Java programming language.
 The size of the primitive data
types does not change with
changing the operating system
Primitive Data Types: Boolean
 The Boolean data type is used to store only two possible values: true and false.
 They can be used to check whether two values are equal or not.
 The default boolean value is False.
 Boolean type’s size depends on the Java Virtual Machine.
 Syntax:
boolean <variable name>=<data value>
 Example:
boolean bl=false;
System.out.println(bl);//Printing the false boolean value
boolean ch="Sdfsd"; //Compiler will show compiler error
Primitive Data Types: char
 The char datatype is used to store a single character/letter enclosed in the single parenthesis.
 It stores lowercase and uppercase characters.
 It takes memory space of 16 bits or 2 bytes.
 The values stored range between 0 to 65536.
 Syntax:
char <variable name>=<data value>
 Example:
char var1='a';
char var2 = 'A';
System.out.print(ch); //Printing the value of var1
System.out.print(var2); //Printing the value of var2
Primitive Data Types: Byte
 The byte is the smallest data type among all the integer data types.
 It is an 8-bit signed two’s complement integer.
 Its value-range lies between -128 to 127 (inclusive)
 Its default value is 0.
 It can also be used in place of "int" data type.
 Syntax:
 Example:
byte byteVar;
byte a=123;
System.out.print(a); //Printing 123
Primitive Data Types: Short
 Short is a 16-bit signed two’s complement integer.
 It stores whole numbers with values ranging from -32768 to 32767.
 Its default value is 0.
 Syntax:
short <variable name>=<data values>;
 Example:
short a=123;
System.out.println(a); //Printing the 123
short b= 32768; //Compiler will show error due to out of range value
Primitive Data Types: Int
 The int data type is a 32-bit signed two's complement integer.
 Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive).
 Its default value is 0.
 Syntax:
int <variable name>=<data values>
 Example:
int a = 100000, int b = -200000
Primitive Data Types: Long
 The long data type is a 64-bit two's complement integer.
 Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive).
 Its default value is 0L.
 The long data type is used when you need a range of values more than those provided by int.
 Syntax:
long <variable name>=<data values>L
 Example:
long a=123123123L;
System.out.println(a); //Printing the value of a long
b=232342342342; //Compiler will show error due to
//the out of range of long values
Primitive Data Types: Example
class IntegerDataTypes
{
public static void main(String args[]) {
int a = 10;
short s = 2;
byte b = 6;
long l = 125362133223l;
System.out.println("The integer variable is " + a + '\n');
System.out.println("The short variable is " + s + '\n');
System.out.println("The byte variable is " + b + '\n');
System.out.println("The long variable is " + l);
}
}
Primitive Data Types: Float
 The float data type is a single-precision 32-bit IEEE 754 floating point.
 Its value range is unlimited.
 It can have a 7-digit decimal precision. It ends with an ‘f’ or ‘F’. Its default value = 0.0f
 It can stores fractional numbers ranging from 3.4e-038 to 3.4e+038
 Syntax:
 Example:
float <variable name>=<data value>
float f1 = 234.5f
Primitive Data Types: double
 The double data type is similar to float. The difference between the two is that is double twice the
float in the case of decimal precision.
 It is a double-precision 64-bit or 8 bytes IEEE 754 floating-point
 It can have a 15-digit decimal precision
 Its default value = 0.0d
 It cab stores fractional numbers ranging from 1.7e-308 to 1.7e+308
 Syntax:
double <variable name>=<data value>
 Example:
double d = 876.765d;
Primitive Data Types: Example
class FloatDataTypes
{
public static void main(String args[]) {
float f = 65.20298f;
double d = 876.765d;
System.out.println("The float variable is " + f);
System.out.println("The double variable is " + d);
}
}
Primitive Data Types: Range
Java Scanner
 Scanner class in Java is found in the java.util package.
 Java provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
 The Java Scanner class provides nextXXX() methods to return the type of value
such as nextInt(), nextByte() , nextShort(), next(),
nextLine(), nextDouble(), nextFloat(), nextBoolean(),
etc.
 Before using the Scanner class, you need to create an instance of it:
Scanner scanner = new Scanner(System.in);
Java Scanner: Reading Inputs
 The Scanner class provides various methods to read different types of input. Some
commonly used methods include:





nextInt(): Reads the next token of input as an integer.
nextDouble(): Reads the next token of input as a double.
nextLine(): Reads the next line of input as a string.
nextBoolean(): Reads the next token of input as a boolean.
next().charAt(0): Reads the character.
Example: int num = scanner.nextInt();
Java Scanner: Addition of 2 nos.
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st no.:");
int a = sc.nextInt();
System.out.println("Enter 2nd no.:");
int b = sc.nextInt();
int c=a+b;
System.out.println("Addition of 1st and 2nd nos is:"+""+c);
}
}
Non-Primitive Data Types
 Non-primitive data types or reference data types refer to instances or objects.
 They cannot store the value of a variable directly in memory.
 They store a memory address of the variable.
 Non-primitive data types are user-defined.
 Programmers create them and can be assigned with null.
 All non-primitive data types are of equal size.
Non-Primitive Data Types: String
 The String data type stores a sequence of characters.
 It is predefined in Java.
 String literals are enclosed in double quotes.
 Syntax:
String <string_variable_name> = “<sequence_of_characters>”;
OR
String <string_variable_name> = new String(“<sequence_of_characters>”);
Non-Primitive Data Types: Array
 An array holds elements of the same type.
 It is an object in Java, and the array name (used for declaration) is a reference value that
carries the base address of the continuous location of elements of an array.
 A Java array variable can also be declared like other variables with [] after the data type.
 Example:
Non-Primitive Data Types: Array
 Syntax:
// Declaration of array
<data_type>[] <array_name> = new <data_type>[size];
// Declaration and Initialization of array at the same time
<data_type> <array_name> [] = {array_item_values};
 Example:
int[] arr = new int[5];
int arr[] = {1,2,3,4,5}; // Declaration &Initialization as well
Arrays
 An array is a collection of variables of the same type, referred to by a common name.
 In Java, arrays can have one or more dimensions, although the one-dimensional array is the
most common.
 Arrays are used for a variety of purposes because they offer a convenient means of grouping
together related variables.
 For example, you might use an array to hold a record of the daily high temperature for a
month, a list of stock price averages, or a list of your collection of programming books
 The principal advantage of an array is that it organizes data in such a way that it can be easily
manipulated.
 Also, arrays organize data in such a way that it can be easily sorted.
Arrays: One-Dimensional
 A one-dimensional array is a list of related variables.
 For example, you might use a one-dimensional array to store the account numbers of the
active users on a network.
 Syntax: type array-name[ ] = new type[size];
 Since arrays are implemented as objects, the creation of an array is a two-step process.
 First, you declare an array reference variable.
 Second, you allocate memory for the array, assigning a reference to that memory to the
array variable
 Example: int sample[] = new int[10];
Arrays: One-Dimensional - Example
class Main
{
public static void main (String args[])
{
int sample[] = new int[10];
int i;
for (i = 0; i < 10; i = i + 1)
sample[i] = i;
for (i = 0; i < 10; i = i + 1)
System.out.println ("This is sample[" + i + "]: " + sample[i]);
}
}
Arrays: Multi-Dimensional - TwoD
 A two-dimensional array is, in essence, a list of one-dimensional arrays.
 To declare a two-dimensional integer array table of size 10, 20 you would write
int table[][] = new int[10][20]
class TwoD
{ public static void main (String args[])
{
int t, i;
int table[][] = new int[3][4];
for (t = 0; t < 3; ++t)
{
for (i = 0; i < 4; ++i)
{
table[t][i] = (t * 4) + i + 1;
System.out.print (table[t][i] + " ");
}
System.out.println (); } }
}
Arrays: Three or More Dimensions
 Java allows arrays with more than two dimensions.
 Syntax: type name[ ][ ]...[ ] = new type[size1][size2]...[sizeN];
 Example: 4 x 10 x 3 three-dimensional integer array.
int multidim[][][] = new int[4][10][3];
Arrays: Three or More Dimensions
class Squares
{ public static void main (String args[])
{
int sqrs[][] = {
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
int i, j;
for (i = 0; i < 10; i++)
{for (j = 0; j < 2; j++)
System.out.print (sqrs[i][j] + " ");
System.out.println ();
} }
}
Problem: Compute Sum and Average of Array Elements
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n, sum = 0;
float average;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum: " + sum);
average = (float) sum / n;
System.out.println("Average: " + average);
}}
Problem: Compute Sum and Average of Array Elements
Hint: Use the length property of the array to get the size of the array.
class Main {
public static void main(String[] args)
{
int[] numbers = {2, -9, 0, 5, 12, 25, 22, 9, 8, 12};
int sum = 0;
Double average;
// access all elements using for each
loop
// add each element in sum
for (int number: numbers) {
sum += number;
}
// get the total number of elements
int arrayLength = numbers.length;
// calculate the average
// convert the average from int to double
average = ((double)sum / (double)arrayLength);
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
}
}
Problem: Largest element in the array
for(int i=0;i<n;i++)
//Use to hold an element
{
for(int j=i+1;j<n;j++)
//Use to check for rest of the elements
{
if(arr[i]<arr[j])
//Compare and swap
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
Problems:
1. Even and Odd elements in two separate arrays
2. Add an Element in a given Position in an Array
3. Find Maximum Difference Between Two Elements in an Array
4. Increment every Element of an Array by One
5. https://www.w3resource.com/java-exercises/array/index.php
Operators
 Operators in Java can be classified into 5 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
Operators
Operator Type
Category
Precedence
postfix
expr++ expr--
prefix
++expr --expr +expr -expr ~ !
multiplicative
*/%
additive
+-
shift
<< >> >>>
comparison
< > <= >= instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
logical AND
&&
logical OR
||
Ternary
ternary
?:
Assignment
assignment
= += -= *= /= %= &= ^= |= <<= >>= >>>=
Unary
Arithmetic
Shift
Relational
Bitwise
Logical
Assignment 1
To be Submit
before 5th
March
String Functions
• The string represents an array of character
values, and the class is implemented by
three interfaces such as Serializable,
Comparable, and CharSequence interfaces.
• It represents the sequence of characters in a
serialized or comparable manner.
• We use double quotes to represent a string
in Java:
String type = "Java";
• Java Strings are Immutable
Create a String in Java
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
// print Java
// print Python
// print JavaScript
Create a String in Java
public class StringExample
{
public static void main (String args[])
{
String s1 = "java"; //creating string by Java string literal
char ch[] = { 's', 't', 'r', 'i', 'n', 'g', 's' };
String s2 = new String (ch); //converting char array to string
String s3 = new String ("example"); //creating Java string by new keyword
System.out.println (s1);
System.out.println (s2);
System.out.println (s3);
}}
Java String Operations
• Get the Length of a String
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length);
}
}
Java String Operations
• Join Two Java Strings
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Java String Operations
• Compare Two Strings
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}}
Java String: Methods
No. Method
1
char charAt(int index)
2
int length()
3
static String format(String format, Object... args)
4
static String format(Locale l, String format, Object... args)
5
String substring(int beginIndex)
6
String substring(int beginIndex, int endIndex)
7
boolean contains(CharSequence s)
8
static String join(CharSequence delimiter, CharSequence... elements)
9
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
10 boolean equals(Object another)
11 boolean isEmpty()
12 String concat(String str)
13 String replace(char old, char new)
14 String replace(CharSequence old, CharSequence new)
15 static String equalsIgnoreCase(String another)
16 String[] split(String regex)
17 String[] split(String regex, int limit)
18 String intern()
19 int indexOf(int ch)
20 int indexOf(int ch, int fromIndex)
21 int indexOf(String substring)
22 int indexOf(String substring, int fromIndex)
23 String toLowerCase()
24 String toLowerCase(Locale l)
25 String toUpperCase()
26 String toUpperCase(Locale l)
27 String trim()
28 static String valueOf(int value)
Description
It returns char value for the particular index
It returns string length
It returns a formatted string.
It returns formatted string with given locale.
It returns substring for given begin index.
It returns substring for given begin index and end index.
It returns true or false after matching the sequence of char value.
It returns a joined string.
It returns a joined string.
It checks the equality of string with the given object.
It checks if string is empty.
It concatenates the specified string.
It replaces all occurrences of the specified char value.
It replaces all occurrences of the specified CharSequence.
It compares another string. It doesn't check case.
It returns a split string matching regex.
It returns a split string matching regex and limit.
It returns an interned string.
It returns the specified char value index.
It returns the specified char value index starting with given index.
It returns the specified substring index.
It returns the specified substring index starting with given index.
It returns a string in lowercase.
It returns a string in lowercase using specified locale.
It returns a string in uppercase.
It returns a string in uppercase using specified locale.
It removes beginning and ending spaces of this string.
It converts given type into string. It is an overloaded method.
Control Statements
Control Statements: Decision-Making / Selection Statements
1. if Statement
if(condition) {
// block of code to be executed if the condition is true
}
Example:
String role = "admin";
if(role == "admin") {
System.out.println("Admin screen is loaded");
}
Control Statements: Decision-Making / Selection Statements
2. if-else Statement
if (condition) {
// If block executed when the condition is true
}
else {
// Else block executed when the condition is false
}
Example:
String role = "user";
if(role == "admin") {
System.out.println("Admin screen is loaded");
}
else {
System.out.println("User screen is loaded");
}
Control Statements: Decision-Making / Selection Statements
3. Nested if-else Statement
if (condition) {
// If block code to be executed if condition is true
if (nested condition) {
// If block code to be executed if nested condition is true
}
else {
// Else block code to be executed if nested condition is false
}
}
else {
// Else block code to be executed if condition is false
}
Control Statements: Decision-Making / Selection Statements
3. Nested if-else Statement
Example:
int age = 20;
String gender = "male";
if (age > 18) {
// person is an adult
if (gender == "male") {
// person is a male
System.out.println("You can shop in the men's section on the 3rd Floor");
} else {
// person is a female
System.out.println("You can shop in the women's section on 2nd Floor");
}
} else {
// person is not an adult
System.out.println("You can shop in the kid's section on 1st Floor");
}
Control Statements: Decision-Making / Selection Statements
4. if-else-if Ladder
if(condition1) {
// Executed only when the condition1 is true
}
else if(condition2) {
// Executed only when the condition2 is true
}
.
.
.
.
else {
// Executed when all the conditions mentioned above are true
}
Control Statements: Decision-Making / Selection Statements
4. if-else-if Ladder
Example:
String browser = "chrome";
if(browser == "safari") {
System.out.println("The browser is safari");
}
else if(browser == "edge") {
System.out.println("The browser is edge");
}
else if(browser == "chrome"){
System.out.println("The browser is chrome");
}
else {
System.out.println("Not a supported browser");
}
Control Statements: Decision-Making / Selection Statements
5. switch Statement
switch (expression) {
case value1:
//code block of case with value1
break;
case value2:
//code block of case with value2
break;
.
.
case valueN:
//code block of case with valueN
break;
default:
//code block of default value
}
Control Statements: Decision-Making / Selection Statements
5. switch Statement
Example:
String browser = "chrome";
switch (browser)
{
case "safari":
System.out.println("The browser is Safari");
break;
case "edge":
System.out.println("The browser is Edge");
break;
case "chrome":
System.out.println("The browser is Chrome");
break;
default:
System.out.println("The browser is not supported");
}
Control Statements: Loop Statements
1. While Statement
• entry-control looping statement
while (condition)
{
// code block to be executed
}
Control Statements: Loop Statements
1. While Statement
Example:
public class WhileLoopDemo {
public static void main(String args[]) {
int num = 10;
while (num > 0) {
System.out.println(num);
// Update Section
num--;
}
}
}
Control Statements: Loop Statements
2. do-while Loop
• exit-control looping statement - its boolean condition is evaluated post
first execution of the body of the loop
do
{
// code block to be executed
} while (condition);
Control Statements: Loop Statements
2. do-while Loop
Example:
public class Main {
public static void main(String args[]) {
int num = 10;
do {
System.out.println(num);
num--;
} while (num > 0);
}
}
Control Statements: Loop Statements
3. for Loop
• a for loop statement consists of the initialization of a variable, a condition,
and an increment/decrement value, all in one line.
• It executes the body of the loop until the condition is false.
• If the condition results in true then the loop body is executed otherwise
the for loop statement is terminated.
for (initialization; condition; increment/decrement)
{
// code block to be executed if condition is true
}
Control Statements: Loop Statements
3. for Loop
Example:
public class ForLoopDemo
{
public static void main (String args[])
{
for (int num = 10; num > 0; num--)
System.out.println ("The value of the number is: " + num);
}
}
Control Statements: Loop Statements
4. for-each Loop
• Enhanced for loop statement -don’t have to handle the increment operation.
• Traverse through elements of an array or a collection in Java.
• It executes the body of the loop for each element of the given array or collection.
• Cannot skip any element of the given array or collection.
• Cannot traverse the elements in reverse order using the for-each loop control
statement in Java.
for(dataType variableName : array | collection)
{
// code block to be executed
}
Control Statements: Loop Statements
4. for-each Loop
Example:
public class Main
{
public static void main (String args[])
{
int[] array = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
System.out.println ("Elements of the array are: ");
for (int elem:array)
System.out.println (elem);
}
}
Control Statements: Jump/Branching Statements
1. Break Statement
• Terminate a case block in a switch statement.
• To exit the loop explicitly, even if the loop condition is true.
• Use as the alternative for the goto statement along with java labels, since java
doesn’t have goto statements.
• The break statement cannot be used as a standalone statement in Java. It must be
either inside a switch or a loop.
for(condition) {
// body of the loop
break;
}
while(condition) {
// body of the loop
break;
}
Control Statements: Loop Statements
1. Break Statement
Example:
for (int index = 0; index < 10; index++)
{
System.out.println ("The value of the index is: " + index);
if (index == 3)
{
break;
}
}
Control Statements: Jump/Branching Statements
2. Continue Statement
• Ignore the rest of the code in the loop body and continue from the next iteration.
• Bypasses every line in the loop body after itself, but instead of exiting the loop, it
goes to the next iteration.
for(condition) {
// body of the loop
continue;
//the statements after this won't be executed
}
while(condition) {
// body of the loop
continue;
// the statements after this won't be executed
}
Control Statements: Loop Statements
2. Continue Statement
Example:
System.out.println ("The odd numbers between 1 to 10 are: ");
for (int number = 1; number <= 10; number++)
{
if (number % 2 == 0)
continue;
System.out.println (number);
}
Control Statements: Jump/Branching Statements
3. Return Statement
• Return from a method explicitly.
• The return statement transfers the control back to the caller method of the current
method.
void method() {
// body of the method
return;
}
Control Statements: Loop Statements
3. Return Statement
Example:
public class ReturnStatementDemo {
public static String search(int key) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int element : numbers) {
if (element == key) {
return "Success";
// Putting statements post this return statement
// Will throw compile-time error
}
}
return "Failure";
}
public static void main(String[] args) {
System.out.println(search(3));
System.out.println(search(10));
}
}
Properties of OOP
Properties of OOP: Abstraction
• It reduces complexity.
• It avoids delicacy.
• Eases the burden of maintenance
• Increase security and confidentially
Properties of OOP: Abstraction
• It reduces complexity.
• It avoids delicacy.
• Eases the burden of maintenance
• Increase security and confidentially
Properties of OOP: Encapsulation
• Allows us to bind data and
functions of a class into an
entity.
• It protects data and
functions from outside
interference and misuse.
• Provides security.
• Example: Class
Properties of OOP: Encapsulation
• Allows us to bind data and functions of a
class into an entity.
• It protects data and functions from outside
interference and misuse.
• Provides security.
• Example: Class
Properties of OOP: Inheritance
• Code Reusability
• Modularity and Organized Code
• Ease of Maintenance
• Promotes Polymorphism
• Facilitates Code Extensibility
Properties of OOP: Polymorphism
• Flexibility and Adaptability
• Code Reusability
• Enhanced Readability
• Simplified Code Maintenance
Properties of OOP: Polymorphism
• Flexibility and Adaptability
• Code Reusability
• Enhanced Readability
• Simplified Code Maintenance
Properties of OOP
OOP
System
Class in OOP
• A class is a construct created in OOP languages that enables creation of objects.
• Also known as blueprint or template or prototype from which objects are created.
• It defines members (variables and methods).
• It provides initial values for state (member variables or attributes), and implementations of
behavior (member functions or methods)
Defining Class:
Class contains variable declarations and method definitions
 Variables describes the attributes of an object.
 It can be instance or static or final variables
 Methods handle the behavior of an object.
 It can be instance methods or static methods
Defining Class:
Members of Class:
 A class contains members which can either be variables(fields) or methods (behaviors)
Member Variables in Java
• A variable declared within a class(outside any method) is known as an instance variable.
• A variable declared within a method is known as local variable.
• Variables with method declarations are known as parameters or arguments.
• A class variable can also be declared as static whereas a local variable cannot be static
Members
of Class:
public class Fee
{
Instance Variable
int bal;
public static int deposit()
{
Local Variable
int d;
d= 5000;
bal = bal + d;
return d;
}
public static int withdrawal(int a)
{
bal = bal – a;
Parameter /
Argument
return a;
}
public static void ledger()
{
System.out.println(bal);
}
Method (member functions) in OOP
 Method is an object’s behavior i.e., action applied to the object
 It’s related to class or object
 Example: “Lion” is an object then its behaviors are roar, walk, run etc.
Object in Java
An object has three characteristics:
Class in Java
Syntax to declare a class:
class <class_name>{
field;
method;
}
public class Main {
int x = 10;
}
Object inside Class
declares a class named ‘Main’
public class Main {
int x = 10;
instance variable (or member variable) x of type int and
initializes it with the value 10
// To create an object of Main, specify the class name, followed by
the object name, and use the keyword new
This method is the entry point for
public static void main(String[] args) {
the Java program and is called
Main myObj = new Main();
when the program starts
System.out.println(myObj.x);
}
}
The keyword new is used to instantiate a new
object, and myObj is the reference variable
pointing to the newly created object
Multiple Objects
public class Main {
int x = 10;
public static void main(String[] args) {
Main myObj1 = new Main();
Main myObj2 = new Main();
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Objects and References
Reference can be created for any type of classes such as concrete classes, abstract
classes and interfaces.
Declare a variable (object reference) of type class after defined a class
Student stud1;
Employee emp1;
 The new operator is used to create an object of that reference type
Employee emp = new Employee();
Object references are used to store objects
new operator
 Dynamically allocates memory for an object
 Creates the object on the heap
 Returns a reference to it
 The reference is then stored in the variable
Access Specifiers / modifier in Java
Access Specifiers / modifier in Java
 Defines an accessible scope of the variable, methods and classes.
 User can change the accessible level of fields, constructors, methods, and class
by applying the access modifier on it.
Modifier
Default
Private
Description
declarations are visible only within the package (package private)
declarations are visible within the class only
Protected
Public
declarations are visible within the package or all subclasses
declarations are visible everywhere
Private Access Modifier
 Private means “only visible within the enclosing class”
 Most restrictive access modifier
 Classes and interfaces cannot be declared with a private modifier unless it is a
nested class.
 Methods, functions and variables with the scope of this modifier are accessible
only within their particular class.
 Usage of this modifier is useful to hide data from the outside world
Private Access Modifier: Example – B.java
class A
{
private void display()
{
System.out.println(“HelloWorld”);
}
}
class B
{
public static void main(String args[])
{
A obj = new A();
obj.display();
}
}
Private Access Modifier: Example – B.java
class A
{
public void display()
{
System.out.println(“HelloWorld”);
}
}
class B
{
public static void main(String args[])
{
A obj = new A();
obj.display();
}
}
Public Access Modifier
Accessible everywhere.
No scope restriction.
This modifier has the widest scope and maximum visibility.
The keyword <public> is essentially used to set the scope
of this class as the public access modifier in Java.
Public Access Modifier: Example – A.java
public class A
{
public void display()
{
System.out.println(“Helloworld”);
}
}
class B {
public static void main(String args[])
{
A obj = new A();
obj.display();
}
}
Protected Access Modifier
 The members of this access modifier are accessible by the same package as well as
by other packages but only through the means of inheritance
 Any class or data member declared with the protected keyword will be accessible
by the package and subclasses.
 Specified using the keyword protected
 The protected access modifier has more accessibility than private and defaults
access modifiers. But it has less visibility than the public access modifier
Protected Access Modifier: Example – Dog.java
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
Default Access Modifier
 If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered.
 The default modifier is accessible only within package. It cannot be accessed from
outside the package.
 It provides more accessibility than private
Default Access Modifier: Example – B.java
class A {
void showData() {
System.out.println("DefaultModifiers Example");
}
}
public class B {
public static void main(String args[])
{
A obj = new A();
obj.showData();
}
}
Access Specifiers / modifier in Java
Access Specifiers / modifier in Java
Access
Modifier
Private
Default
Protected
Public
Within Class
Yes
Yes
Yes
Yes
Within
Package
No
Yes
Yes
Yes
Outside
package by
subclass only
No
No
Yes
Yes
Outside
package
No
No
No
Yes
Static Class Members (variables and methods)
 The static keyword is used to share the same variable or method of a given class.
 We can access it without creating an instance of the class in which they are defined
ClassName.staticVariable
ClassName.staticMethod()
 Static class is a nested class and it doesn't need the reference of the outer class.
 Using reference to the Object of the class:
Classname obj = new Classname ();
obj.staticMethod();
 Static class can access only the static members of its outer class.
 When a value is stored in a static variable, it is not stored in object of the class.
1. Static Variable
public class Main {
static int staticVariable = 10;
public static void main(String[] args) {
System.out.println(Main.staticVariable);
}
}
1. Static Variable
 The static variable gets memory only once in the class area at the time of class
loading
 It makes your program memory efficient (i.e., it saves memory).
 Shared among all objects of the class.
 Static variables are rarely used other than being declared as constants.
 Constants are variables that are declared as public/private, final (not change), and
static. Constant variables never change from their initial value.
 E.g., private static price; // price is private static
variable like local variable
 Public static final variables are global constants.
 E.g., public static final String PRODUCT= “Steel";
// PRODUCT is a constant
2. Static Methods
 Most common example of a static method is the main( )method
 Static methods can only access directly the static members and manipulate a
class’s static variables.
public class Main
{
public static void show ()
//static method
{
System.out.println ("Welcome");
}
public static void main (String args[])
{
Main.show ();
//calling static method using class name
}
}
Problem 1:
Program to get the cube of a given number using the static method
class Main{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result = Main.cube(5);
System.out.println(result);
}
}
Problem 2: Static variable and Static method
public class Main {
static int staticVariable = 42;
static void staticMethod() {
System.out.println("Static Variable: " + staticVariable);
System.out.println("This is a static method.");
}
public static void main(String[] args) {
Main.staticMethod(); // Calling static method
System.out.println("Accessing static variable: " + Main.staticVariable);
}
}
Problem 3: Simple Calculator (add/sub)
public class Main {
static int result = 0;
// Static method to add two numbers
static void add(int a, int b) {
result = a + b;
}
// Static method to subtract two numbers
static void subtract(int a, int b) {
result = a - b;
}
// Static method to get the result
static int getResult() {
return result;
}
public static void main(String[] args) {
// Perform addition
add(10, 5);
System.out.println("Result after addition: " + getResult());
// Perform subtraction
subtract(20, 8);
System.out.println("Result after subtraction: " + getResult());
}
}
Constructors
 Constructor is a special method that defined within the class.
 Constructor is invoked automatically whenever an object of the class is created.
 At the time of calling constructor, memory locations for the object is allocated in
the memory.
 The primary purpose of a constructor is to initialize the state of an object. It sets
the initial values for the object's attributes or performs any necessary setup
 Every time an object is created using the new() keyword.
Rules to define Constructors
 A constructor has the same name as the class name
 A constructor should not have a return type
 A constructor can be defined with any access specifier (private, public)
 A class can contain more than one constructor, So it can be overloaded
Constructors Example
class Student
{
Constructor //The Constructor
Student() {}
}
Student A = new Student();
Class
curly braces
Object
//The Constructor
Student() {
};
Constructors Example
class Studnet
{
String Name;
int Age;
Studnet(String name, int age) {
Name=name;
Age=age;
}
}
public class Main {
public static void main(String[] args) {
Studnet A = new Studnet("Roy", 40);
System.out.println(A.Name);
System.out.println(A.Age);
}
}
Constructor Initialization
Constructor Types
Default
Constructor
Parameterized
Default constructor
A constructor is called “Default
Constructor” when it doesn’t have
any parameter.
Also known as no-arg constructor
Syntax: <class_name>(){}
class Student
{
//creating a default constructor
Student ()
{
System.out.println (“Name");
}
}
public class Main{
public static void main (String args[])
{
//calling a default constructor
Student b = new Student ();
}
}
Parameterized constructor
class Main {
 It has a specific number of
parameters.
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming");
}
 It provide different values to
distinct objects
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
}
}
Constructor: Problem 1
 Create a class named Book with the following attributes:
• title (String)
• author (String)
• pageNumber (int)
 Include a default constructor that initializes the attributes with the following default values:
• title: “Java: The Complete Reference”
• author: “Herbert Schildt”
• pageNumber: 1313
 Create an object of the Book class using the default constructor and display the information
about the book.
Constructor: Problem 1 - Solution
class Book {
String title;
String author;
int pageNumber;
// Default Constructor
Book() {
// Initialize default values
title = "Java: The Complete Reference";
author = "Herbert Schildt";
pageNumber = 1313;
}
public class Main {
public static void main(String[] args) {
// Create a Book object using the
default constructor
Book defaultBook = new Book();
// Display information about the book
System.out.println("Default Book
Information:");
defaultBook.displayInfo();
}
}
// Display information about the book
void displayInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Page Number: " + pageNumber);
}
}
Constructor: Problem 2
 Create a class named Rectangle with the following attributes:
• length (int)
• width (int)
 Include a parameterized constructor that takes two parameters (length and width)
and initializes the attributes with the provided values.
 Include a method named calculateArea that computes and returns the area of the
rectangle using the formula: area = length * width.
 Create an object of the Rectangle class using the parameterized constructor with
length = 5 and width = 3
 Calculate and display the area of the rectangle.
Constructor: Problem 2 - Solution
class Rectangle {
int length;
int width;
// Parameterized Constructor
Rectangle(int length1, int width1) {
// Initialize attributes with provided values
length = length1;
width = width1;
}
// Method to calculate and return the area of the rectangle
double calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
// Create a Rectangle object using the parameterized constructor
Rectangle rectangle = new Rectangle(5, 3);
// Calculate and display the area of the rectangle
double area = rectangle.calculateArea();
System.out.println("Area of the rectangle: " + area);
}
}
this Keyword
 It is a reference variable that refers to the current object.
 Usage:
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
this Keyword – Example 1
public class Main
{
static int a = 5000;
static int b = 2000;
Main (int a, int b)
{
this.a = a; // refers current instance variable
this.b = b; // refers current instance variable
}
void display ()
{
System.out.println ("a = " + a + " b = " + b);
}
public static void main (String[]args)
{
Main obj1 = new Main (100, 10);
obj1.display ();
}}
this Keyword – Example 2
public class Student {
String name;
int age;
// Parameterized constructor
public Student(String name, int age) {
// Using "this" to refer to instance variables
this.name = name;
this.age = age;
}
// Method to display information about the student
public void displayInfo() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
public static void main(String[] args) {
Student student = new Student(“Vamsi Krishna", 20);
// Calling the displayInfo method
student.displayInfo();
}}
Static Block
 A static block is a block of code enclosed in braces, preceded by the keyword static.
 Example:
static
{
System.out.println("i am static block");
}
 The statements within the static block are executed automatically when the class is loaded into JVM.
 A class can have any number of static blocks and they can appear anywhere in the class
 They are executed in the order of their appearance in the class
 JVM combines all the static blocks in a class as single static block and executes them
 User can invoke static methods from the static block and they will be executed as and when the static block gets
executed
Static Block - Example
class Exstaticblock
{
static
{
System.out.println ("i am static 1");
}
Exstaticblock ()
{
System.out.println ("i am constructor");
}
static void method ()
{
System.out.println ("i am static method");
}
static
{
System.out.println ("i am static 3");
}
public static void main (String arg[])
{
Exstaticblock obj = new Exstaticblock ();
method ();
}
static
{
System.out.println ("i am static 2");
}
}
Encapsulation
Encapsulation
Groups data and methods within a class to provide a protective barrier over
internal implementation details.
It allows the construction of objects that encapsulate data and reveal only the
methods or interfaces required for interaction with the outside world.
This method encourages information concealment by prohibiting direct access
to an object's internal state.
Types – Public, Private, Protected Access Modifier & Getters and Setters
Encapsulation – Access Modifier
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public void deposit(double amount) {
// Add validation and logic for deposit
balance += amount;
}
public void withdraw(double amount) {
// Add validation and logic for withdrawal
balance -= amount;
}
public double getBalance() {
return balance;
}
public static void main(String[]
args) {
BankAccount account = new
BankAccount("1234567890");
account.deposit(100.0);
account.withdraw(50.0);
System.out.println("Current Balance: "
+ account.getBalance());
}
}
Encapsulation – Getter and Setter
public class Main {
private int accountNumber;
private int accountBalance;
// getter method
public int getAccountBalance() {
return this.accountBalance;
}
// setter method
public void setAccountNumber(int num) {
this.accountNumber = num;
}
public static void main(String[] args) {
Main main = new Main();
main.setAccountNumber(123456789);
System.out.println("Account Number: " + main.accountNumber);
}
}
Problem 1: Create a Java program to model information
about a person.
Person.java
 Create a Person class with the following specifications:
 Three private fields: name (String), age (int), and country (String).
 Provide getter and setter methods for each field (getName(), setName(), getAge(),
setAge(), getCountry(), setCountry()).
 The class should allow creating an instance of a person with no initial values.
 Each setter should update the respective field with the given value.
 Each getter should return the value of the respective field.
 Additionally, include a main method inside the Person class to:
 Create an instance of Person.
 Set values for the person's name, age, and country using the setter methods.
 Retrieve these values using the getter methods.
 Print out the retrieved values.
Problem 1: Solution
// Person.java
class Main {
private String name;
private int age;
private String country;
public static void main(String[] args) {
// Create an instance of Person
Person person = new Person();
// Set values using setter methods
person.setName("Vamsi");
person.setAge(25);
person.setCountry("India");
public String getName() {
return name;
}
// Get values using getter methods
String name = person.getName();
int age = person.getAge();
String country = person.getCountry();
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
// Print the values
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Country: " + country);
public void setAge(int age) {
this.age = age;
}
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
End of Module 1
Download