MODULE – 1
(Object-Oriented Programming – Fundamentals)
By:
Dr. Nagendra Panini Challa
Assistant Professor, Senior Grade 2
SCOPE, VIT-AP University, India
Basics of OOP this Keyword
Features of OOP Encapsulation
Introduction to Java Inheritance: Inheritance
Objects and Classes in Java Hierarchies
Defining Classes Super and Subclasses
Methods access control
Access Specifiers super keyword
Static Members final keyword
Constructors final classes and methods
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 2
As the name suggests, Object-Oriented Programming or OOPs refers to languages
that uses objects in programming.
Object-oriented programming combines a group of data attributes with functions
or methods into a unit called an "object."
The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 3
A simple example would be a class representing a person.
The person class would contain attributes to represent information such as the
person’s age, name, height, etc.
The class definition might also contain functions such as "sayMyName" which
would simply print that person’s name to the screen.
Each person object would contain different data attributes since each person is
unique.
A family could be constructed by instantiating person objects from the class for
each member of the family.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 4
This OO programming style is pervasive in popular programming languages such
as Java, C++, Python, JavaScript and C# among others.
By defining sets of classes that represent and encapsulate objects in a program, the
classes can be organized into modules, improving the structure and organization of
software programs.
Thus, developers often use OOP as a tool when they need to create complex
programs since they are easier to reason in terms of classes and their relationships.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 5
Procedural oriented Programming
program is a list of instructions to the computer
Object Oriented Programming
program is composed of a collection objects that communicate with
each other
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 6
Procedural Oriented Programming
Program is divided into small parts called as functions
It follows top down approach
No access specifiers in this paradigm
Adding new data and function is not easy
It is not having proper data hiding mechanism so that it is less
secure
In this model, function is more important than data
Ex: C, FORTRAN, PASCAL etc...
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 7
Object Oriented Programming
In this model, Program is divided into small parts called Objects
It follows bottom up approach
It have access specifiers like Public, Private and Protected
Adding new data and functions is easy
It is more secure
In this model, data is more important than function
Ex: C++, Java, Python etc...
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 8
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 9
Any entity that has state and behavior is known
as an object. For example, a chair, pen, table,
keyboard, bike, etc.
A dog is an object because it has states
like color, name as well as behaviors
like barking, eating.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 10
A Java object is a member (also called an
instance) of a Java class.
Each object has an identity, a behaviour
and a state.
The state of an object is stored in fields
(variables), while methods (functions)
display the object’s behaviour.
For Example, Pen
Objects are created at runtime is an object.
from templates, which are also known
as classes.
Java objects are very similar to the objects Its name is
we can observe in the real world. Reynolds; color is
Ex: A cat, a lighter, a pen, or a car are all white, known as
objects. its state.
It is used to write,
so writing is its
behavior.
P can be
identifier
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 11
Student (Class) {
Defined by an instance
Collection of objects is called class.
(Object)
It is a logical entity.
An object is an instance of a class. Name, Roll number,
Branch (Properties of
We can create many instances of a class.
the object)
A Java class uses variables to define data
fields and methods to define actions.
Read(), Write() and
A class can also be defined as a blueprint Play() (Tasks
from which you can create an individual Performed)
object.
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 12
It is a process of hiding implementation details and exposes only the functionality
to the user.
In abstraction, we deal with ideas and not events.
This means the user will only know “what it does” rather than “how it does”.
Real-Life Example-
A driver will focus on the car functionality (Start or Stop, Accelerate or Break), he
or she does not bother about how the Accelerate or brake mechanism works
internally. And this is how the abstraction works.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 13
Encapsulation is the process of wrapping code and data together into a single
unit.
Real-Life Example: A capsule which is mixed of several medicines. The medicines
are hidden data to the end user.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 14
Polymorphism is the ability to perform many things in many ways.
The word Polymorphism is from two different Greek words- poly and morphs.
“Poly” means many, and “Morphs” means forms. So polymorphism means many
forms.
Real-life Example:
A delivery person delivers items to the user. If it’s a postman he will deliver the
letters. If it’s a food delivery boy he will deliver the foods to the user. Like this
polymorphism implemented different ways for the delivery function.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 15
Inheritance is the process of one class inheriting properties and methods from
another class in Java.
Inheritance is used when we have a relationship between objects.
Inheritance in Java is implemented using extends keyword.
Real-life Example:
The planet Earth and Mars inherits the super class Solar System and Solar system
inherits the Milky Way Galaxy. So Milky Way Galaxy is the top super class for Class
Solar System, Earth and Mars.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 16
Java is a high level programming language and a platform.
Java is a high level, robust, object-oriented and secure programming language.
Any hardware or software environment in which a program runs, is known as a
platform.
Since Java has a runtime environment (JRE), it is called a platform.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 17
Click to add text
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 18
Click to add text
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 19
JVM (Java Virtual Machine) is an abstract machine. Loads code, Verifies code,
Executes code, Provides runtime environnent where bytecode can be executed.
The Java Runtime Environment (JRE) is a set of software tools which are used for
developing Java applications.
The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 20
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 21
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 22
Click to add text
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 23
It is an important section but optional for a Java program.
The comments may be single-line, multi-line, and documentation comments.
Single-line Comment It starts with a pair of forwarding slash (//) // Hello VIT-AP
Multi-line Comment It starts with a /* and ends with */. We write between these two
symbols.
/∗It is an example of multiline comment∗/
Documentation Comment It starts with the delimiter (/**) and ends with */.
/∗∗ I t i s an example of documentation comment∗/
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 24
The package declaration is optional. It is placed just after the documentation
section.
In this section, we declare the package name in which the class is placed.
Note that there can be only one package statement in a Java program. It must be
defined before any class and interface declaration.
It is necessary because a Java class can be placed in different packages and
directories based on the module they are used.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 25
For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name.
For Example
package scope; //where scope is the package name
package VIT-AP.scope;
//where VIT-AP is the root directory and scope is the subdirectory
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 26
The package contains the many predefined classes and interfaces.
If we want to use any class of a particular package, we need to import that class.
The import statement represents the class stored in the other package.
We use the import keyword to import the class.
It is written before the class declaration and after the package statement.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 27
We use the import statement in two ways, either import a specific class or import
all classes of a particular package.
In a Java program, we can use multiple import statements.
For example:
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all the class of the java.util package
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 28
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 29
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 30
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 31
It is an optional section. We can create an interface in this section if required.
We use the interface keyword to create an interface.
An interface is slightly different from the class.
It contains only constants and method declarations.
Another difference is that it cannot be instantiated.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 32
We can use interface in classes by using the implements keyword.
An interface can also be used with other interfaces by using the extends keyword.
For example:
interface car
{
void start();
void stop();
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 33
It is vital part of a Java program.
Without the class, we cannot create any Java program.
A Java program may conation more than one class definition.
We use the class keyword to define the class.
The class is a blueprint of a Java program.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 34
It contains information about user-defined methods, variables, and constants.
Every Java program has at least one class that contains the main() method.
For example:
class Student //class definition
{
public static void main(String[] args)
//statements
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 35
In a Java program, the variables and constants are defined just after the class
definition.
The variables and constants store values of the parameters.
It is used during the execution of the program.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 36
We can also decide and define the scope of variables by using the modifiers.
It defines the life of the variables.
For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 37
It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method.
In other words, it is an entry point of the class.
It must be inside the class.
Inside the main method, we create objects and call the methods.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 38
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 39
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 40
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 41
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 42
We use the following statement to define the main() method:
public static void main(String args[])
{
}
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 43
The main() is the starting point for JVM to start execution of a Java program.
Without the main() method, JVM will not execute the program.
The syntax of the main() method is:
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 44
public: It is an access specifier. We should use a public keyword before the main()
method so that JVM can identify the execution point of the program. If we use
private, protected, and default before the main() method, it will not be visible to
JVM.
For Example
public class Test {
static void main(String [] args)
{
System.out.println(”Hello World”);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 45
static: When java runtime starts, there is no object of the class present. That’s why
the main method has to be static so that JVM can load the class into memory and
call the main method. If the main method won’t be static, JVM would not be able to
call it because there is no object of the class is present.
For example:
public class Test {
public void main(String [] args){
System.out.println(”Hello World”);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 46
void: In Java, every method has the return type. Void keyword acknowledges the
compiler that main() method does not return any value, that’s why it’s return type is
void.
For example:
public class Test {
public static void main(String [] args){
return 0;
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 47
main(): It is a default signature which is predefined in the JVM. It is called by JVM
to execute a program line by line and end the execution after completion of this
method.
String args[]: The main() method also accepts some data from the user. It accepts
a group of strings, which is called a string array. It is used to hold the command line
arguments in the form of string values.
What happens if the main() method is written without String args[]?
The program will compile, but not run, because JVM will not recognize the
main() method. Remember JVM always looks for the main() method with a
string type array as a parameter.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 48
Variables are containers for storing data values. In Java, there are different types of
variables
String - stores text, such as ”Hello”. String values are surrounded by double quotes
int- stores integers (whole numbers), without decimals, such as 123 or -123
float- stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as ’a’ or ’B’. Char values are surrounded by
single quotes
boolean - stores values with two states: true or false
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 49
To create a variable, you must specify the type and assign it a value:
type variableName = value ;
Where type is one of Java’s types (such as int or String), and variableName is the
name of the variable (such as x or name).
The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
String name = ”John ”; System.out. println(name);
To create a variable that should store a number, look at the following example:
int myNum = 15;
System.out. println(myNum );
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 50
You can also declare a variable without assigning the value, and assign the
value later:
int myNum; myNum = 15;
System . out . println(myNum ) ;
Note that if you assign a new value to an existing variable, it will overwrite
the previous value:
int myNum = 15;
myNum = 20; // myNum is now 20
System . out . println(myNum);
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 51
To declare more than one variable of the same type, you can use a comma-
separated list
int x = 5, y = 6, z = 50; System.out.println(x + y + z);
One Value to Multiple Variables
int x,y,z;
x = y = z = 50; System.out.println(x + y + z);
A demonstration of how to declare variables of other types:
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = ’D’ ;
boolean myBool = true ;
String myText = ”Hello ”;
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 52
Names can contain letters, digits, underscores, and dollar signs
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain whitespace
Names can also begin with dollar and underscore
Names are case sensitive (”myVar” and ”myvar” are different variables)
Reserved words (like Java keywords, such as int or boolean) cannot be used as
names
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 53
There are three types of variables in java:
local variable:
A variable declared inside the body of the method is called local variable.
Instance variable:
A variable declared inside the class but outside the body of the method, is called
instance variable.
Static variable/Class Variable
A variable which is declared as static is called static variable. It cannot be local. You
can create a single copy of static variable and share among all the instances of the
class. Memory allocation for static variable happens only once when the class is
loaded in the memory.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 54
Data types are divided into two groups:
Primitive data types - includes byte, short, int, long, float, double, boolean
and char
Non-primitive data types - such as String, Arrays and Classes
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 55
Arithmetic Operators
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 56
Assignment Operators
Example
int x = 10;
x += 5;
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 57
Comparison Operators Logical Operators
For Example
x<5 && x<10
x<5||x<4
!(x < 5 && x < 10)
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 58
Write a Java program with and without a main method and understand its outcome.
Write a Java program to print Hello World as output.
Write a Java program to add numbers using multiple variables.
Write a java program to print the reverse of given input string.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 59
/*Program name: Palindrome*/ public static void main(String args[])
{
//Author's name: Mathew //variables to be used in program
int r, s=0, temp;
/*Palindrome is number or string that will remains the same int x; //It is the number variable to be checked for palindrome
Scanner sc=new Scanner(System.in);
When we write that in reverse order. Some example of
System.out.println("Enter the number to check: ");
palindrome is 393, 010, madam, etc.*/ //reading a number from the user
x=sc.nextInt();
//imports the Scanner class of the java.util package //logic to check if the number id palindrome or not
temp=x;
import java.util.Scanner; while(x>0)
//class definition {
r=x%10; //finds remainder
public class CheckPalindromeNumber s=(s*10)+r;
x=x/10;
{ }
if(temp==s)
//main method System.out.println("The given number is palindrome.");
} else
System.out.println("The given number is not palindrome.");
}
Output:
Enter the Number to check: 121
The given number is palindrome
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 60
There are many devices where Java is currently used.
Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as irctc.co.in, javatpoint.com, etc.
Enterprise Applications such as banking applications.
Mobile
Games, etc.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 61
Object-oriented programming has several advantages over procedural
programming
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY ”Don’t Repeat Yourself”, and makes the code
easier to maintain, modify and debug.
OOP makes it possible to create full reusable applications with less code and
shorter development time
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 62
Classes and objects are the two main aspects of object-oriented programming
A class is a template for objects, and an object is an instance of a class.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 63
In Java, an object is created from a class.
Syntax for creation of an Object in Java
ClassName object = new ClassName ();
To create an object of Main, specify the class name, followed by the object name, and
use the keyword new
Example
public class VIT {
int x=5;
public static void main(String [] args)
{
VIT myObj = new VIT ( ) ; Output: 5
System.out. println(myObj.x);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 64
public class Main {
int x=5;
public static void main(String [] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out. println(myObj1.x);
System.out. println(myObj2.x);
}} Output:
5
5
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 65
You can also create an object of a class and access it in another class.
This is often used for better organization of classes (one class has all the attributes and
methods, while the other class holds the main() method (code to be executed)).
Main.java
public class Main {
int x=5;
}
Second.java
class Second {
public static void main(String [] args) {
Main myObj = new Main ( ) ;
System.out. println(myObj.x);
}
Output: 5
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 66
Example for declaration of variables in class
public class Main {
int x=5; int y=3;
}
Accessing Attributes The following example will create an object of the Main class,
with the name myObj.
We use the x attribute on the object to print its value:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 67
public class Main {
int x = 10;
public static void main(String [] args) {
Main myObj = new Main ( ) ;
myObj.x = 25; // x is now 25
System.out. println(myObj.x); Output:
25
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 68
If we don’t want the ability to override existing values, declare the attribute as final
Example
public class Main {
final int x = 10;
public static void main(String [] args) {
Main myObj = new Main ( ) ;
myObj.x = 25; // will generate an error : cannot be assigned
System.out. println(myObj.x);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 69
If you create multiple objects of one class, you can change the attribute values in
one object, without affecting the attribute values in the other
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
public class Main {
int x=5;
public static void main(String [] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 70
We can specify as many attributes as we want
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) { Output:
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname); Name: John Doe
Age: 24
System.out.println("Age: " + myObj.age);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 71
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known
as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 72
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
In the following example, myMethod(); is used to print a text (the action), when it is
called:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
Output:
I just got executed
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 73
A method can also be called multiple times:
Example:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
Output:
myMethod();
myMethod(); I just got executed!
myMethod(); I just got executed!
}} I just got executed!
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 74
public class Main {
static void myStaticMethod() {
System.out.println("Static Methods"); //In static method no need to create an object for achieving output
}
public void myPublicMethod() {
System.out.println("Non Public Methods");
} Output:
public static void main(String[] args)
{ Static Methods
myStaticMethod(); Non Public Methods
Main myObj = new Main();
myObj.myPublicMethod(); //In public method output will be executed only when object is created
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 75
public class Main {
public void fullThrottle() {
System.out.println("The car is going fast");
}
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}
public static void main(String [] args) { Output:
Main myCar = new Main ( );
myCar. fullThrottle (); The car is going fast
myCar . speed (200); Max speed is: 200
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 76
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes.
public class Main {
int x;
public Main() { //constructor
x=5;
} Output:
public static void main(String [] args) {
Main myObj = new Main ( ) ; 5
System.out. println(myObj.x);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 77
The parameterized constructors are the constructors having a specific number of
arguments to be passed.
The purpose of a parameterized constructor is to assign user-wanted specific
values to the instance variables of different objects.
A parameterized constructor is written explicitly by a programmer.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 78
Note that the constructor name must match the class name, and it cannot have a return
type (like void).
Also note that the constructor is called when the object is created.
Constructor Parameters
public class Main {
int x;
public Main( int y) { //parameterised constructors
x=y;
}
public static void main(String [] args) { Output:
Main myObj = new Main (5);
System.out. println(myObj.x); 5
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 79
You can have as many parameters as you want in constructors
Example:
public class Main {
int modelYear ;
String modelName;
public Main(int year , String name) //Parameterised constructor
{
modelYear = year ;
modelName = name; }
public static void main(String [] args) {
Main myCar = new Main(1969 , ”Mustang ”);
System.out.println(myCar.modelYear + ” ”+myCar.modelName);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 80
Example
public class Student {
int roll_no; String stu_name;
Student(int i, String n) { // Parameterized constructor
roll_no = i; stu_name = n; }
void display() { System.out.println(roll_no+" "+stu_name); }
public static void main(String args[]) {
Student s1 = new Student(1,"Adithya");
Student s2 = new Student(2,"Jai");
s1.display();
s2.display(); }}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 81
1. Write a java program that calculates the perimeter and area of rectangle for given length
and width, use constructor to set length and width.
2. Design and write a class to represent a bank account that includes the following
members:
a. Data members
Owner name
Account number
Balance amount in the account
b. Methods members
To assign initial values
To deposit an amount
To withdraw an amount after checking balance
To display the owner name and balance
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 82
3.a. Write a program to print the names of students by creating a Student class. If no
name is passed while creating an object of Student class, then the name should be
"Unknown", otherwise the name should be equal to the String value passed while
creating object of Student class.
b. Create a class named 'Programming'. While creating an object of the class, if nothing
is passed to it, then the message "I love programming languages" should be printed. If
some String is passed to it, then in place of "programming languages" the name of that
String variable should be printed.
For example, while creating object if we pass "Java", then "I love Java" should be
printed.
4. Suppose you have a Piggie Bank with an initial amount of $50 and you have to add
some more amount to it. Create a class 'AddAmount' with a data member named
'amount' with an initial value of $50. Now make two constructors of this class as follows:
1 - without any parameter - no amount will be added to the Piggie Bank
2 - having a parameter which is the amount that will be added to Piggie Bank
Create object of the 'AddAmount' class and display the final amount in Piggie Bank.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 83
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class.
There are four types of Java access specifiers:
- Public : accessible from everywhere
- Private : accessible within the same class only
- Default : accessible by the classes of the same package
- Protected : accessible by the classes of the same package and the
subclasses residing in any package
The access specifiers can be strictly ordered:
public > protected > default > private
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 84
public- The class is accessible by any other class
public class Main {
public static void main(String [] args) {
System.out.println(”Hello World”);
}}
default-The class is only accessible by classes in the same package. This is used
when you don’t specify a specifier/modifier.
class MyClass {
public static void main(String [] args) {
System.out.println(”Hello World”);
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 85
public-The code is accessible for all classes
public class Main {
public String fname = ”John ”;
public String lname = ”Doe”;
pubic String email = ”john@doe .com”; int age = 24;
}
class Second1 {
public static void main(String [] args) {
Main myObj = new Main ( ) ;
System.out.println(”Name: ” + myObj.fname + ” ” + System.out.println(”Email: ” +
myObj.email); System.out.println(”Age: ” + myObj.age);
}
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 86
private-The code is only accessible within the declared class
public class Main {
private String fname = ”John”;
private String lname = ”Doe”;
private String email = ”john@doe .com”;
private int age = 24;
}
class test{
public static void main(String [] args) {
Main myObj = new Main ( ) ;
System.out.println(”Name: ” + myObj.fname + ” ” + System.out.println(”Email: ” +
myObj.email); System.out.println(”Age: ” + myObj.age);
}
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 87
Protected-The code is accessible in the same package and subclasses.
class Person {
protected String fname = ”John ”;
protected String lname = ”Doe”;
protected String email = ”john@doe .com”;
protected int age = 24;
}
class Student extends Person {
private int graduationYear = 2018;
public static void main(String [] args) {
Student myObj = new Student ( ) ;
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 88
System.out.println(”Name: ” + myObj.fname + ” ” + myOb
System.out.println(”Email: ” + myObj.email); System.out.println(”Age: ” +
myObj.age); System.out.println(”Graduation Year: ” + myObj.gra
}}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 89
default-The code is only accessible in the same package. This is used when you
don’t specify a modifier. You don’t need to specify any keyword for this. It is created
by JVM itself.
class Person {
String fname = ”John ”;
String lname = ”Doe”;
String email = ”john@doe .com”; int age = 24;
public static void main(String [] args) {
Person Ob = new Person();
System.out.println(”Name: ” +Ob.fname +” ”+Ob.lnam System.out.println(”Email: ”
+Ob.email); System.out.println(”Age: ” +Ob.age);
}
}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 90
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 91
class Student{ //class definition void display(){
int rollno; // Instance variable 1 System.out.println(rollno+" "+name+" "+fee);}
}
String name; // Instance variable 2
class TestThis1{
float fee; // Instance variable 3 public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student Student s2=new Student(112,"sumit",6000f);
(int rollno,String name,float fee) s1.display();
{ s2.display();
rollno=rollno; // local variable 1 }}
name=name; //local variable 2 Output:
fee=fee; // local variable 3
0 null 0.0
}
0 null 0.0
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 92
In the previous example, parameters (formal arguments) and instance variables
are same. So, we are using this keyword to distinguish local variable and instance
variable.
Local variables: Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
Instance variables Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 93
public class A //class definition
{
static int m=100; //static or instance variable
void method()
{
int n=90; // local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 94
If local variables(formal
arguments) and instance
variables are different, there
is no need to use this
keyword
class Student{ void display(){System.out.println(rollno+" "+na
me+" "+fee);}
int rollno;
}
String name;
class TestThis2{
float fee; public static void main(String args[]){
Student(int rollno,String name,float fee){ Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
this.rollno=rollno; // formal arguments s1.display();
this.name=name; s2.display();
}}
this.fee=fee; Output:
}
111 ankit 5000.0
112 sumit 6000.0
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 95
If local variables(formal
arguments) and instance
variables are different, there
is no need to use this
keyword
class Student{
void display(){System.out.println(rollno+" "+name+" "+
int rollno; fee);}
String name; }
float fee;
class TestThis3{
Student(int rollno,String name,floapublic static void main(String args[]){
t fee){
Student s1=new Student(111,"ankit",5000f);
this.rollno=rollno; // Student s2=new Student(112,"sumit",6000f);
formal arguments
s1.display();
this.name=name; s2.display();
this.fee=fee; }}
Output:
} 111 ankit 5000.0
112 sumit 6000.0
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 96
Encapsulation is defined as the wrapping up of data under a single unit.
It is the mechanism that binds together code and the data it manipulates.
Technically in encapsulation, the variables or data of a class is hidden from any
other class and can be accessed only through any member function of its own class
in which it is declared.
Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables
It is more defined with setter and getter method.
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 97
// get method for age to access
// private variable geekAge
// Java program to demonstrate encapsulation
public int getAge() { return geekAge; }
class Encapsulate {
// private variables declared // get method for name to access
// private variable geekName
// these can only be accessed by
// public methods of class public String getName() { return geekName; }
private String geekName; // get method for roll to access
private int geekRoll; // private variable geekRoll
private int geekAge; public int getRoll() { return geekRoll; }
// set method for age to access
// private variable geekage
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 98
public void setAge(int newAge) { geekAge = newAge; }
// set method for name to access
▪ // private variable geekName
▪ public void setName(String newName)
▪{
▪ geekName = newName;
▪}
▪
▪ // set method for roll to access
▪ // private variable geekRoll
▪ public void setRoll(int newRoll) { geekRoll = newRoll; }
▪}
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 99
In the below program, the class Encapsulate is
encapsulated as the variables are declared as
private. The get methods like getAge() , getName() ,
getRoll() are set as public, these methods are used
to access these variables. The setter methods like
public class TestEncapsulation {
setName(), setAge(), setRoll() are also declared as
public static void main(String[] args) public and are used to set the values of the
variables.
{
Encapsulate obj = new Encapsulate(); // Displaying values of the variables
System.out.println("Geek's name: " +
obj.getName());
// setting values of the variables System.out.println("Geek's age: " + obj.getAge());
obj.setName("Harsh"); System.out.println("Geek's roll: " + obj.getRoll());
obj.setAge(19); // Direct access of geekRoll is not possible
Output: // due to encapsulation
obj.setRoll(51);
// System.out.println("Geek's roll: " +
Geek's name: Harsh // obj.geekName);
Geek's age: 19 }
Geek's roll: 51 }
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 100
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 101
Object Oriented Programming (OOP), SCOPE, VIT-AP University, India 21-02-2023 102