0% found this document useful (0 votes)
1 views37 pages

Oopjava Unit 1

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts using Java, covering key topics such as classes, objects, inheritance, polymorphism, and encapsulation. It highlights the advantages of OOP, including modularity, reusability, and ease of maintenance, while also contrasting it with procedural programming. Additionally, it discusses the applications of OOP in various fields like GUI development, web development, and game development.
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)
1 views37 pages

Oopjava Unit 1

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts using Java, covering key topics such as classes, objects, inheritance, polymorphism, and encapsulation. It highlights the advantages of OOP, including modularity, reusability, and ease of maintenance, while also contrasting it with procedural programming. Additionally, it discusses the applications of OOP in various fields like GUI development, web development, and game development.
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

Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & A.

Neelima

Object Oriented Programming through JAVA


UNIT -I
_______________________________________________________________________________________________________
SYLLABUS:
Introduction to OOP: Basic concepts of OOP, Differences between Procedural and Object-
Oriented Programming, Advantages of OOP, Applications of OOP.
Introduction to JAVA: Structure of JAVA, Features of JAVA, Data Types, JAVA Tokens,
Control Statements.
Classes & Objects: Introduction, Class Declaration, Class Members, Declaration of Class
Objects, Access Control for Class Members, Static Variables and Methods, User input to
programs, Command Line Arguments, Method overloading.
Constructors: Default Constructor, Parameterized Constructor, Copy Constructor and
Constructor Overloading, This Keyword.
_______________________________________________________________________________________________________

Basic Concepts of Object-Oriented Programming

It is necessary to understand some of the key concepts used extensively in object-oriented


programming. These include:

• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
• Reusability
• Delegation
• Genericity
We shall discuss these concepts in some detail in this section.
Class
A class is a data-type that has its own members i.e. data members and member functions. It
is the blueprint for an object in object oriented programming language. It is the basic
building block of object oriented programming in C++. The members of a class are accessed
in programming language by creating an instance of the class.
Some important properties of class are −
• Class is a user-defined data-type.
• A class contains members like data members and member functions.
• Data members are variables of the class.
• Member functions are the methods that are used to manipulate data members.
• Data members define the properties of the class whereas the member functions
define the behavior of the class.
A class can have multiple objects which have properties and behavior that in common for

CIC Sagi Rama Krishnam Raju Engineering College(A) 1


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

all of them.

Objects

Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program
must handle.
The fundamental idea behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some real
word entity. For example: consider an example named Amit; Amit is 25 years old and his
salary is 2500. The Amit may be represented in a computer program as an object. The data
part of the object would be (name: Amit, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrieve of data,
change age, change of salary). In general even any user –defined type-such as employee may
be used. In the Amit object the name, age and salary are called attributes of the object
The figure shows two notations that are popularly used in object-oriented analysis and
design.

Data Abstraction and Encapsulation

The wrapping up of data and functions into a single unit (called class) is known
as encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class
can access it. These functions provide the interface between the object’s data and the
program. This insulation of the data from direct access by the program is called data hiding
or information hiding.
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost, and functions to operate
on these attributes. They encapsulate all the essential properties of the objects that are to
be created. The attributes are sometimes called data members because they hold
information. The functions that operate on these data are sometimes called methods or
member functions.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types
(ADT).

CIC Sagi Rama Krishnam Raju Engineering College(A) 2


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Inheritance

Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification. For example,
the bird ‘robin’ is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The
principle behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in Figure.

Figure: Property inheritance

In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined features
of both the classes. The real appeal and power of the inheritance mechanism is that it allows
the programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor
the class in such a way that it does not introduce any undesirable side-effects into the rest
of the classes

Note that each sub-class defines only those features that are unique to it. Without
the use of classification, each class would have to explicitly include all of its features.

Polymorphism
The name defines polymorphism is multiple forms, which means polymorphism is
the ability of object oriented programming to do some work using multiple forms. The
behavior of the method is dependent on the type or the situation in which the method is
[Link] process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Let’s take a real life example, a person can have more than one behavior depending
upon the situation like a woman a mother, manager and a daughter and this define her
behavior. This is from where the concept of polymorphism came from.

CIC Sagi Rama Krishnam Raju Engineering College(A) 3


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

In C++ programming language, polymorphism is achieved using two ways. They are
operator overloading and function overloading.
Operator overloading In operator overloading and operator can have multiple behavior
in different instances of usage.
Function overloading Functions with the same name that can do multiple types based on
some condition.
Figure illustrates that a single function name can be used to handle different number
and different types of arguments. This is something similar to a particular word having
several different meanings depending on the context. Using a single function name to
perform different types of tasks is known as function overloading.

Figure: Polymorphism
Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in


response to the call. Dynamic binding (also known as late binding) means that the code
associated with a given procedure call is not known until the time of the call at run-time. It
is associated with polymorphism and inheritance. A function call associated with a
polymorphic reference depends on the dynamic type of that reference.

Consider the procedure “draw” in above figure. By inheritance, every object will
have this procedure. Its algorithm is, however, unique to each object and so the draw
procedure will be redefined in each class that defines the object. At run-time, the code
matching the object under current reference will be called.

Message Passing

An object-oriented program consists of a set of objects that communicate with each


other. The process of programming in an object-oriented language, therefore, involves the
following basic steps:

1. Creating classes that define objects and their behavior,


2. Creating objects from class definitions, and
3. Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes

CIC Sagi Rama Krishnam Raju Engineering College(A) 4


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

it easier to talk about building systems that directly model or simulate their real-world
counterparts.

A message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and the information to be sent. Example:

Objects have a life cycle. They can be created and destroyed. Communication with an object
is feasible as long as it is alive.

Reusability

Object oriented technology allows reusability of the classes by extending them


to other classes using inheritance. Once a class is defined, the other programmer can also
use it in their programs. The programmer can also add new feature to the derived classes.
The verified and checked qualities of base classes need not to be redefined. Thus, the
reusability saves the time. In figure, class A is reused and class B is created. Again class B is
reused and class C is created.

Figure: Reusability

Delegation

In OOP, two classes can be joined in two ways: (a) Inheritance, (b) Delegation. Both
these ways provide reusability of the class.

In Inheritance one class can be derived from the other class. The relationship between these
two classes is called as kind of relationship. For example if class Y is derived from class X,
then class Y is known as kind of X. Figure 1.8 (a) explains this point.

CIC Sagi Rama Krishnam Raju Engineering College(A) 5


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Figure: 1.8 Relationships between two classes: (a) Kind of relationship (Inheritance) (b)
has a relationship (Delegation)

The second type of relationship is has a relationship. When object of one class is
used as data member in the other class, such composition of objects is known as delegation.
As shown in Figure 1.8(b) class C has two data members. These two data members are
objects of class A and B, such relationship between the classes in known as has a
relationship.

Genericity

The software components of a program have more than one version depending on
the data types of arguments. This feature allows declaration of variables without specifying
exact data type. The compiler identifies the data type at run time. The programmer can
create a function that can be used for any type of data. The template feature in C++ allows
generic programming.

Differences between Procedural and Object-Oriented Programming

Procedural Programming (POP) and Object-Oriented Programming (OOP) differ in their


approach to structuring code:

Procedural Programming:
- Focuses on functions or procedures to operate on data.
- Functions are separate from data and are called to perform operations.
- Does not support encapsulation, inheritance, or polymorphism inherently.

Object-Oriented Programming:
- Focuses on objects that contain both data and methods to operate on that data.
- Promotes encapsulation, which bundles data and methods together.
- Supports inheritance and polymorphism, allowing for more flexible and reusable code.
Object-Oriented Programming Procedural Programming
Feature
(OOP) (POP)
Procedure or function
Basic Unit Object (combines data and methods)
(operates on data)
Data and
Encapsulated within objects Separate from functions
Functions
Focus On objects and interactions On procedures and algorithms

CIC Sagi Rama Krishnam Raju Engineering College(A) 6


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Object-Oriented Programming Procedural Programming


Feature
(OOP) (POP)
High, due to encapsulation and
Modularity Lower, as code is more linear
modular design
Data Hiding Achieved through encapsulation Not inherently supported
Supported, allowing classes to
Inheritance Not supported
inherit properties
Supported, enabling one interface to
Polymorphism Not supported
be used for different data types
High, hides complex implementation Lower, functions are more
Abstraction
details explicit
High, through inheritance and Limited, often requires code
Code Reusability
polymorphism duplication
Ease of Easier, due to modularity and Harder, as changes can affect
Maintenance reusability many parts of the program
Development Can be longer initially, but shorter Generally shorter for small
Time for large and complex systems programs
Example
Java, C++, Python, C# C, Fortran, Pascal
Languages
Real-World Excellent for modeling real-world Less intuitive for real-world
Modeling scenarios scenarios
Better suited for large, complex Better suited for small to
Scalability
applications medium-sized applications

Advantages of OOP

Object oriented technology provides many advantages to the programmer and the user.
This technology solves many problems related to software development, provides
improved quality and low cost software.
1. Object oriented programs can be comfortably upgraded.
2. Using inheritance, we can eliminate redundant program code and continue the use of
previously defined classes.
3. The technology of data hiding facilitates the programmer to design and develop safe
programs that do not disturb code in other parts of the program.
4. The encapsulation feature provided by OOP languages allows programmer to define the
class with many functions and characteristics and only few functions are exposed to the
user.
5. All object oriented programming languages allows creating extended and reusable parts
of programs.
6. Object oriented programming changes the way of thinking of a programmer. This
results in rapid development of new software in a short time.
7. Objects communicate with each other and pass messages.

Some more advantages of OOP are

CIC Sagi Rama Krishnam Raju Engineering College(A) 7


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Modularity: Breaks down complex programs into manageable modules.


Reusability: Classes can be reused across programs, reducing code duplication.
Encapsulation: Keeps data safe from outside interference and misuse.
Inheritance: Promotes code reuse and simplifies development.
Polymorphism: Improves flexibility and integration.
Abstraction: Simplifies design by hiding complex details.
Ease of Maintenance and Upgrading: Enhances maintainability and scalability.
Enhanced Productivity: Speeds up development and reduces complexity.
Improved Collaboration: Facilitates better teamwork and parallel development.
Real-World Modeling: Aligns closely with real-world scenarios.

Applications of OOP

OOP is widely used in various fields of software development due to its flexibility and
modularity. Some common applications include:

1. Graphical User Interface (GUI) Applications: OOP languages like Java and C# are
commonly used to develop GUI applications.
2. Web Development: OOP principles are used in server-side languages like Java, C#, and
PHP to create dynamic web applications.
3. Mobile Development: OOP languages such as Swift for iOS development and
Java/Kotlin for Android development are widely used.
4. Game Development: OOP is fundamental in game development for managing game
entities, behaviors, and interactions.
5. Simulation and Modeling: OOP languages like Python and C++ are used to create
complex simulations and models.
6. Enterprise Applications: OOP languages are used to build large-scale enterprise
applications due to their modularity and reusability.

Introduction to JAVA

Java is a high-level, class-based, object-oriented programming language designed to have


as few implementation dependencies as possible. It is a general-purpose programming
language that allows developers to write code once and run it anywhere (WORA), meaning
that compiled Java code can run on all platforms that support Java without the need for
recompilation. Java applications are typically compiled to bytecode that can run on any Java
Virtual Machine (JVM) regardless of the underlying computer architecture.

History of JAVA

Early Development

• 1991: Java's development began at Sun Microsystems, led by James Gosling and
team, under the project name "The Green Project."
• 1992: The language was initially called Oak, developed for a home-entertainment
controller device.

Transition to Java

• 1994: The team shifted focus to web technology, adapting Oak for web applets.
• 1995: Oak was renamed Java, and Java 1.0 was officially released.

CIC Sagi Rama Krishnam Raju Engineering College(A) 8


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Growth and Adoption

• 1996: Java Development Kit (JDK) 1.0 was released, promoting the "Write Once, Run
Anywhere" (WORA) philosophy.
• 1998: Java 2 (J2SE 1.2) introduced significant improvements and split into Standard
(J2SE), Enterprise (J2EE), and Micro (J2ME) editions.

Later Developments

• 2004: Java 5.0 (J2SE 5.0) added generics, metadata, and enhanced loops.
• 2006: Sun Microsystems made Java open source.
• 2009: Oracle Corporation acquired Sun Microsystems and Java.

Modern Era

• 2014: Java 8 introduced lambda expressions, the Stream API, and the new Date and
Time API.
• 2017: Java 9 introduced the module system (Project Jigsaw).
• 2018: Oracle adopted a six-month release cadence, with Java 11 designated as a
Long-Term Support (LTS) version.
• 2021: Java 17 was released as the next LTS version.

Features of Java:

Java is a powerful and versatile programming language that provides numerous features to
developers. Here are some of the key features of Java:

Simple: Java has a clean and easy-to-understand syntax, which makes it easy to learn and
use. It eliminates many complex features found in other languages, such as explicit pointers
and operator overloading.

Object-Oriented: Everything in Java is treated as an object. This paradigm helps in


modularizing code and making it reusable. Key concepts include classes, objects,
inheritance, polymorphism, abstraction, and encapsulation.

Platform-Independent: Java code is compiled into bytecode, which can be executed on any
system with a Java Virtual Machine (JVM). This "write once, run anywhere" capability
makes Java highly portable.

Secure: Java provides a secure environment by offering multiple security features such as
bytecode verification, sandboxing, and the security manager, which help in defending
against malicious code and vulnerabilities.

Robust: Java emphasizes reliability with features such as strong memory management,
exception handling, and garbage collection. It also has a strong type-checking mechanism
that helps in detecting errors at compile time.

Multithreaded: Java has built-in support for multithreading, allowing multiple threads to
run concurrently. This feature helps in developing high-performance, interactive, and
responsive applications.

CIC Sagi Rama Krishnam Raju Engineering College(A) 9


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Distributed: Java has a rich set of APIs and tools for developing distributed applications. It
supports Remote Method Invocation (RMI) and Enterprise JavaBeans (EJB) to create
distributed systems.

High Performance: Java’s performance is improved by using Just-In-Time (JIT) compilers


and efficient garbage collection algorithms. While not as fast as native languages like C or
C++, Java’s performance is sufficient for many applications.

Dynamic: Java is capable of dynamically linking new class libraries, methods, and objects.
It supports dynamic loading of classes, which allows the code to be highly flexible and
extensible.

Architecture-Neutral: The Java compiler generates bytecode, which is architecture-


neutral. This means that the same bytecode can run on any processor architecture,
provided there is a JVM available for that architecture.

Interpreted: Java bytecode is interpreted by the JVM. This allows for platform
independence and enables the code to be executed on any system that has a JVM.

Portable: Java eliminates the platform-specific aspects of its language, making the
compiled code portable. It achieves this by using a standardized, machine-independent
bytecode and a runtime environment.

Structure of JAVA

A typical Java program consists of several parts:

1. Package Declaration: Defines the package name which groups related classes
together.
package [Link];

2. Import Statements: Allow the use of classes from other packages.

import [Link];

3. Class Declaration: Defines a class with its fields and methods.

public class HelloWorld {


// Fields and methods
}

4. Main Method: Entry point of any Java application.

public static void main(String[] args) {


// Code to be executed
}

5. Statements: Instructions that the program executes.

[Link]("Hello, World!");

CIC Sagi Rama Krishnam Raju Engineering College(A) 10


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Example Java Program:

package [Link];
import [Link];
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name + "!");
}}
Java Development Kit (JDK)

The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment (JRE),
an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), and other tools needed for Java development. Here's an overview of
its main components and functionalities:

Key Components of JDK

1. Java Runtime Environment (JRE)


o The JRE provides the libraries, Java Virtual Machine (JVM), and other
components to run applications written in Java. It does not contain tools for
Java development like compilers or debuggers.
2. Java Compiler (javac)
o The Java compiler translates Java source code (.java files) into bytecode
(.class files) that can be executed by the JVM.
3. Java Virtual Machine (JVM)
o The JVM is the engine that runs Java applications. It converts the bytecode
into machine code for execution on the host system.
4. Java Archive Tool (jar)
o The jar tool is used for creating, viewing, and manipulating Java Archive
(JAR) files. JAR files bundle multiple files into a single archive file.
5. Java Documentation Generator (Javadoc)
o Javadoc is a tool for generating API documentation in HTML format from
Java source code.
6. Other Tools
o javap: Disassembler for class files.
o jdb: Java Debugger.
o java: Launcher for Java applications.
o jps: JVM Process Status Tool.
o jstat: Java Virtual Machine Statistics Monitoring Tool.
o jconsole: Java Monitoring and Management Console.
o jshell: Java Shell (REPL) for interactive programming.

Data Types in Java


Java has a rich set of data types that are categorized into two main types: primitive data
types and reference/object data types.

CIC Sagi Rama Krishnam Raju Engineering College(A) 11


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Primitive Data Types


These are the most basic data types in Java:

1. byte
o Size: 8-bit
o Range: -128 to 127
2. short
o Size: 16-bit
o Range: -32,768 to 32,767
3. int
o Size: 32-bit
o Range: -2^31 to 2^31-1
4. long
o Size: 64-bit
o Range: -2^63 to 2^63-1
5. float
Size: 32-bit floating point
o
Range: approximately ±3.40282347E+38F (6-7 significant decimal digits)
o
6. double
o Size: 64-bit floating point
o Range: approximately ±1.79769313486231570E+308 (15 significant
decimal digits)
7. char
o Size: 16-bit Unicode character
o Range: '\u0000' to '\uffff'
8. boolean
o Size: Not precisely defined
o Values: true or false

Reference/Object Data Types


These data types are based on classes and include:

• Classes
• Interfaces
• Arrays
• Strings

JAVA Tokens

Java tokens are the smallest elements of a program that are meaningful to the compiler.
They include:

1. Keywords
o Reserved words that have a predefined meaning in the language. Example:
class, public, static, void, etc.
2. Identifiers
o Names given to classes, methods, variables, etc.
o Example: main, args, Scanner, etc.
3. Literals
o Constant values assigned to variables.
o Example: 123, 3.14, 'A', "Hello", true, false, etc.

CIC Sagi Rama Krishnam Raju Engineering College(A) 12


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

4. Operators
o Symbols that perform operations on variables and values.
o Example: +, -, *, /, =, ==, etc.
5. Separators
o Symbols used to separate statements and blocks of code.
o Example: ;, ,, (), {}, [], etc.

Java Operators

Operators in Java are special symbols that perform specific operations on one, two, or three
operands and then return a result. Java operators can be classified into the following types:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Bitwise Operators
7. Ternary Operator
8. Instanceof Operator

1. Arithmetic Operators

Perform mathematical operations.

• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Modulus (%)

int sum = 5 + 3; // Example: sum is 8


2. Unary Operators

Operate on a single operand.

• Unary Plus (+)


• Unary Minus (-)
• Increment (++)
• Decrement (--)
• Logical Complement (!)

int a = 5;
a++; // Example: a is now 6
3. Assignment Operators

Assign values to variables.

• Simple Assignment (=)


• Add and Assign (+=)
• Subtract and Assign (-=)

CIC Sagi Rama Krishnam Raju Engineering College(A) 13


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

• Multiply and Assign (*=)


• Divide and Assign (/=)
• Modulus and Assign (%=)

int a = 5;
a += 3; // Example: a is now 8
4. Relational Operators

Compare two operands and return a boolean result.

• Equal to (==)
• Not Equal to (!=)
• Greater than (>)
• Less than (<)
• Greater than or Equal to (>=)
• Less than or Equal to (<=)

boolean isEqual = (5 == 3); // Example: isEqual is false


5. Logical Operators

Perform logical operations.

• Logical AND (&&)


• Logical OR (||)
• Logical NOT (!)

boolean result = (true && false); // Example: result is false


6. Bitwise Operators

Perform bit-level operations on integer types.

• Bitwise AND (&)


• Bitwise OR (|)
• Bitwise XOR (^)
• Bitwise Complement (~)
• Left Shift (<<)
• Right Shift (>>)
• Unsigned Right Shift (>>>)

int result = 5 & 3; // Example: result is 1 (binary 0101 & 0011 = 0001)
7. Ternary Operator

Shorthand for the if-else statement.

• Conditional (? :)

int result = (5 > 3) ? 10 : 20; // Example: result is 10


8. Instanceof Operator

Tests whether an object is an instance of a specific class or subclass.

CIC Sagi Rama Krishnam Raju Engineering College(A) 14


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

• Instanceof (instanceof)

String str = "Hello";


boolean isString = str instanceof String; // Example: isString is true

Java Control Statements

Control statements in Java control the flow of execution of the program. They can be
categorized into decision-making statements, looping statements, and jump statements.

1. Decision-Making Statements
if Statement

The if statement evaluates a condition. If the condition is true, the block of code inside the
if statement is executed.

Syntax:

if (condition) {
// code to be executed if condition is true
}
if-else Statement

The if-else statement evaluates a condition. If the condition is true, the block of code
inside the if statement is executed. Otherwise, the block of code inside the else statement
is executed.

Syntax:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
else-if Ladder

The else-if ladder allows you to check multiple conditions. If one condition is true, the
corresponding block of code is executed.

Syntax:

if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
switch Statement

The switch statement allows a variable to be tested for equality against a list of values.

CIC Sagi Rama Krishnam Raju Engineering College(A) 15


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Each value is called a case, and the variable being switched on is checked for each case.

Syntax:

switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
default:
// code to be executed if expression doesn't match any case
}
2. Looping Statements
for Loop

The for loop is used to execute a block of code a specific number of times. It is typically
used when the number of iterations is known beforehand.

Syntax:

for (initialization; condition; increment/decrement) {


// code to be executed
}
while Loop

The while loop is used to execute a block of code as long as a specified condition is true.
The condition is checked before the loop body is executed.

Syntax:

while (condition) {
// code to be executed
}
do-while Loop

The do-while loop is similar to the while loop, but the condition is checked after the loop
body is executed. This ensures that the loop body is executed at least once.

Syntax:

do {
// code to be executed
} while (condition);

3. Jump Statements
break Statement

The break statement is used to exit from a loop or switch statement prematurely.

CIC Sagi Rama Krishnam Raju Engineering College(A) 16


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Syntax:

break;
• continue Statement

The continue statement skips the current iteration of a loop and proceeds to the next
iteration.

Syntax:

continue;
• return Statement

The return statement is used to exit from a method and optionally return a value.

Syntax:

return value; // if method returns a value


// or
return; // if method returns void

Example Program
Here’s an example Java program demonstrating the use of various control statements:

package [Link];

import [Link];

public class ControlStatementsExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// if-else statement
[Link]("Enter a number: ");
int number = [Link]();
if (number > 0) {
[Link]("Number is positive.");
} else {
[Link]("Number is negative or zero.");
}

// for loop
[Link]("Counting to 5:");
for (int i = 1; i <= 5; i++) {
[Link](i);
}

// while loop
[Link]("Enter a positive number to countdown from:");
int countdown = [Link]();
while (countdown > 0) {

CIC Sagi Rama Krishnam Raju Engineering College(A) 17


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

[Link](countdown);
countdown--;
}

// do-while loop
[Link]("This will run at least once:");
int doWhileCounter = -1;
do {
[Link]("do-while loop iteration");
} while (doWhileCounter > 0);

// switch statement
[Link]("Enter a grade (A-F): ");
char grade = [Link]().charAt(0);
switch (grade) {
case 'A':
[Link]("Excellent!");
break;
case 'B':
[Link]("Good job!");
break;
case 'C':
[Link]("Well done!");
break;
case 'D':
[Link]("You passed.");
break;
case 'F':
[Link]("Better try again.");
break;
default:
[Link]("Invalid grade.");
}

// break statement
[Link]("Using break in a loop:");
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
[Link](i);
}

// continue statement
[Link]("Using continue in a loop:");
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
[Link](i);
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 18


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

// return statement
[Link]("Method with return statement:");
printMessage();
}

public static void printMessage() {


[Link]("Hello from the method!");
return;
}
}

Classes & Objects: Introduction

Class:

• A class is a blueprint or template from which objects are created. It defines a type by
bundling data and methods that work on the data into one single unit.
• A class defines the properties (attributes) and behaviors (methods) that the objects
created from the class can have.

Example:

class Car {
// attributes
String color;
String model;

// behavior or method
void drive() {
[Link]("Car is driving");
}
}

Object:

• An object is an instance of a class. It is a real-world entity that has a state (attributes)


and behavior (methods).

Example:

Car myCar = new Car();


[Link] = "Red";
[Link]();

Class Declaration

In Java, a class serves as a blueprint for creating objects. It encapsulates data


(attributes) and behavior (methods) related to a particular concept or entity. The class
declaration defines this blueprint.

CIC Sagi Rama Krishnam Raju Engineering College(A) 19


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Basic Structure of a Class Declaration

A class declaration in Java is straightforward and consists of several key components:

• Keyword class: This keyword is used to declare a class.


• Class Name: The name of the class follows the class keyword. It should be a
meaningful noun that reflects the purpose of the class. The class name should follow
the PascalCase naming convention, where the first letter of each word is capitalized
(e.g., Student, BankAccount, Employee).
• Curly Braces {}: The body of the class is enclosed within curly braces. Inside these
braces, you define the attributes (fields) and methods (functions) of the class.

Example: Simple Class Declaration

class Student {
// Attributes (Fields)
String name;
int age;

// Methods
void study() {
[Link](name + " is studying.");
}
}

Explanation:

• class Student: This line declares a class named Student.


• Inside the class, there are two fields: name and age, which represent the attributes
of a Student object.
• There is also a method study() that defines the behavior of a student.

Key Components of a Class Declaration

Let's dive deeper into each of the components of a class declaration:

a. Class Name

Definition: The class name is a unique identifier for the class. It should be descriptive
enough to convey the purpose of the class. For instance, a class that represents a bank
account might be named BankAccount, while a class representing an employee might be
named Employee.

Naming Convention:

• PascalCase is the convention used in Java for class names. This means each word in
the name begins with an uppercase letter, and there are no spaces or underscores
between words.
• Examples: Student, LibraryBook, CustomerOrder.

CIC Sagi Rama Krishnam Raju Engineering College(A) 20


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

b. Attributes/Fields

Definition: Attributes, also known as fields or member variables, represent the state or
properties of an object. They are variables defined within a class, and each object of the
class has its own copy of these fields (unless they are static).

Types of Fields:

• Instance Variables: These are fields that belong to each instance of the class. For
example, each Student object might have its own name and age.
• Static Variables: These are shared across all instances of the class. If a variable is
declared as static, all instances of the class share the same value of that variable.

Example:

class Car {
String model; // Instance variable
String color;
static int numberOfWheels = 4; // Static variable
}

Explanation: Here, model and color are instance variables, while numberOfWheels is a
static variable shared by all Car objects.

c. Methods

Definition: Methods in a class define the behavior or actions that objects of the class can
perform. Methods are functions that are defined inside the class and can operate on the
class's fields.

Method Declaration:

• A method typically includes a return type, a method name, parentheses that may
enclose parameters, and a body enclosed in curly braces.
• The method name should follow the camelCase naming convention, where the first
word is lowercase, and subsequent words start with an uppercase letter.

Example:

class Student {
String name;
int age;

// Method to display student details


void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}

// Method to set the student's age


void setAge(int newAge) {

CIC Sagi Rama Krishnam Raju Engineering College(A) 21


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

age = newAge;
}
}

Explanation: The Student class has two methods: displayDetails() to print the student's
details and setAge() to update the student's age.

Class Members

Fields (Attributes):

• Fields are variables defined within a class that hold the data for an object.

Example:

class Student {
String name;
int age;
}

Methods:

• Methods define the behavior of an object. They are functions that operate on the
fields of the class.

Example:

class Student {
String name;
int age;

void study() {
[Link](name + " is studying");
}
}

Constructors:

• A constructor is a special method used to initialize objects. The constructor is called


when an object of a class is created.

Example:

class Student {
String name;
int age;

// Constructor
Student(String name, int age) {
[Link] = name;

CIC Sagi Rama Krishnam Raju Engineering College(A) 22


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

[Link] = age;
}
}

Declaration of Class Objects

In Java, objects are instances of classes. When you declare a class, you're essentially defining
a new data type. To use this class, you need to create objects from it. This process involves
using the new keyword and the class constructor.

1. Creating Objects

Syntax:

• The syntax for creating an object involves specifying the class name, followed by a
reference variable, and then using the new keyword to call the constructor of the
class.

Example:

Student student1 = new Student("John", 20);

Explanation:

• Student is the class name.


• student1 is the reference variable that will point to the newly created object.
• new Student("John", 20); creates a new instance of the Student class by invoking the
constructor that takes a name and age as parameters.
• The constructor initializes the object's fields with the provided values ("John" and
20 in this case).
2. Accessing Object Fields and Methods

Once an object is created, you can interact with its attributes (fields) and behaviors
(methods) using the dot . operator. The dot operator allows you to access the fields and
methods of the object.

Accessing Fields:

• Fields (attributes) of an object store data related to that particular instance. You can
read or modify these fields using the dot operator.

Example:

[Link] = "Alice"; // Changing the name field of student1


[Link]([Link]); // Accessing and printing the name field

Explanation:

• [Link] = "Alice"; changes the name field of the student1 object to "Alice".

CIC Sagi Rama Krishnam Raju Engineering College(A) 23


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

• [Link]([Link]); accesses the name field of student1 and prints


it to the console.

Accessing Methods:

• Methods define the behavior of an object. They can be invoked using the dot
operator.

Example:

[Link](); // Calling the study method on student1

Explanation:

• [Link](); calls the study() method of the student1 object. This method might
contain code to print a message like "Alice is studying."
Access Control for Class Members

Access Modifiers in Java

Java provides four levels of access control for class members (fields and methods) using
access modifiers: private, default (no modifier), protected, and public. These modifiers
determine the visibility of class members from different parts of the program.

1. Private Access Modifier

Visibility:

• The private modifier restricts access to the class members within the class itself.
This means that no other class, even within the same package, can directly access
private members.
• It's the most restrictive access level.

Usage:

• Private members are often used for encapsulation, hiding the internal details of a
class from other classes.
• To allow controlled access to these private members, you typically provide public
getter and setter methods.

Example:

class Student {
private String name; // Only accessible within the Student class
private int age;

// Constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;

CIC Sagi Rama Krishnam Raju Engineering College(A) 24


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

// Getter method to access the private name


public String getName() {
return name;
}

// Setter method to modify the private name


public void setName(String name) {
[Link] = name;
}
}

Explanation: In this example, name and age are private, so they cannot be accessed directly
from outside the Student class. However, the public methods getName() and setName()
provide controlled access to the name field.

2. Default Access Modifier (Package-Private)

Visibility:

• If no access modifier is specified, the member has default access (also known as
package-private).
• This means the member is accessible to any other class within the same package but
not to classes in other packages.

Usage:

• Use default access when you want to allow access to class members within the same
package but prevent access from outside the package.

Example:

class Student {
String name; // Accessible within the same package
int age;
}

Explanation: Here, name and age are accessible to all classes in the same package as
Student. However, if you try to access them from a class in a different package, it will result
in a compile-time error.

3. Protected Access Modifier

Visibility:

• The protected modifier allows access within the same package and to subclasses in
other packages.
• It provides a middle ground between default (package-private) and public access.

Usage:

CIC Sagi Rama Krishnam Raju Engineering College(A) 25


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

• Protected members are often used in scenarios where you want to allow subclasses
to access certain members but still want to restrict access to the rest of the program.

Example:

class Student {
protected int rollNumber; // Accessible within the same package and by subclasses

public Student(int rollNumber) {


[Link] = rollNumber;
}
}

// A subclass in the same package


class CollegeStudent extends Student {
public CollegeStudent(int rollNumber) {
super(rollNumber);
}

void displayRollNumber() {
[Link]("Roll Number: " + rollNumber);
}
}

Explanation: The rollNumber field is protected, so it's accessible in CollegeStudent, a


subclass of Student. If CollegeStudent were in a different package, it would still have access
to rollNumber because of the protected modifier.

4. Public Access Modifier

Visibility:

• The public modifier allows access from any other class in any package. Public
members are universally accessible throughout the entire program.

Usage:

• Use public access for methods or fields that you want to expose to all other parts of
the program.
• Common examples include public methods like main() and fields or methods
intended to be part of a class’s API.

Example:

class Student {
public String college; // Accessible from anywhere in the program
public Student(String college) {
[Link] = college;
}
public void displayCollege() {
[Link]("College: " + college);

CIC Sagi Rama Krishnam Raju Engineering College(A) 26


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

}
}

The college field and the displayCollege() method are public, meaning any class from any
package can access them directly.

Summary of Access Modifiers

Modifier Class Package Subclass World

private ✔

Default ✔ ✔

protected ✔ ✔ ✔

public ✔ ✔ ✔ ✔

✔ - Accessible - Not Accessible

Static Variables

Static variables, also known as class variables, are variables that are shared among all
instances of a class. Unlike instance variables, which are unique to each object, static
variables have a single memory location, and all instances of the class refer to this same
memory location.

Characteristics of Static Variables:

1. Shared Across Instances: All instances of the class share the same static variable.
Changing the value of a static variable in one instance affects all other instances.
2. Memory Allocation: Static variables are allocated memory only once, at the time of
class loading, not when objects are created. They remain in memory as long as the
class is loaded, which can be for the duration of the program.
3. Access: Static variables can be accessed directly using the class name, without
needing to create an instance of the class.

For example, ClassName. staticVariable.

Example: Using Static Variables

class Student {
static int totalStudents = 0; // Static variable
String name;

// Constructor increments the static variable


Student(String name) {
[Link] = name;
totalStudents++;
}
void showStudent() {

CIC Sagi Rama Krishnam Raju Engineering College(A) 27


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

[Link]("Student Name: " + name);


}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("John");
Student s2 = new Student("Jane");
Student s3 = new Student("Jack");

// Accessing the static variable


[Link]("Total Students: " + [Link]);
}
}

Explanation: In this example, totalStudents is a static variable that increments each time a
new Student object is created. Since it's static, it counts the total number of Student
instances, and all instances share this count.

Static Methods

Static methods are methods that belong to the class rather than to any specific instance of
the class. They can be called without creating an instance of the class.

Characteristics of Static Methods:

1. No Instance Required: Static methods can be invoked directly using the class name,
without needing to instantiate the class.
2. Access to Static Members: Static methods can directly access other static variables
and static methods. However, they cannot directly access instance variables or
instance methods because static methods do not operate on instances.
3. Use Cases: Static methods are often used for operations that don't require any data
from an instance of the class. Common examples include utility or helper methods
like [Link]() or [Link]().

Example: Using Static Methods

class Student {
static int totalStudents = 0;

// Static method to display total students


static void showTotalStudents() {
[Link]("Total students: " + totalStudents);
}
String name;
Student(String name) {
[Link] = name;
totalStudents++;
}
void showStudent() {
[Link]("Student Name: " + name);
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 28


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("John");
Student s2 = new Student("Jane");

// Calling the static method without creating an instance


[Link]();
}
}

Explanation: The showTotalStudents method is static, so it can be called directly using


[Link]() without needing an object of the Student class. This method
simply prints the value of the static variable totalStudents.

User Input to Programs

Scanner Class

• The Scanner class is part of the [Link] package and is widely used for obtaining
input of primitive types like int, double, float, etc., as well as strings.
• It provides a convenient way to read user input during runtime from different input
sources, such as the keyboard, files, and streams.

How to Use the Scanner Class

• To use the Scanner class, you first need to import it from the [Link] package.
• Create an instance of the Scanner class, usually passing [Link] as an argument to
read input from the standard input stream (keyboard).

Example: Basic Input with Scanner

import [Link];
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the keyboard
Scanner scanner = new Scanner([Link]);

// Prompt the user to enter their name


[Link]("Enter your name: ");
String name = [Link]();

// Display the input received


[Link]("Hello, " + name);
}
}

Explanation:

• new Scanner([Link]): Creates a Scanner object that reads from the keyboard.

CIC Sagi Rama Krishnam Raju Engineering College(A) 29


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

• nextLine(): Reads the entire line of input, including spaces, until the user presses
Enter.

Different Methods of the Scanner Class

The Scanner class provides various methods to read different types of data:

• nextInt(): Reads an integer value.


• nextDouble(): Reads a double value.
• nextFloat(): Reads a float value.
• nextLong(): Reads a long integer value.
• nextBoolean(): Reads a boolean value.
• nextLine(): Reads a whole line of text (useful for strings with spaces).
• next(): Reads the next token (word) as a string, stopping at a space or newline.

Example: Reading Different Data Types

import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Reading an integer
[Link]("Enter your age: ");
int age = [Link]();

// Reading a double
[Link]("Enter your height in meters: ");
double height = [Link]();

// Reading a boolean
[Link]("Are you a student (true/false): ");
boolean isStudent = [Link]();

// Reading a string (next() method)


[Link]("Enter your first name: ");
String firstName = [Link]();

// Reading a whole line (nextLine method)


[Link](); // Consume the newline left-over
[Link]("Enter your full name: ");
String fullName = [Link]();

// Output the values entered


[Link]("Age: " + age);
[Link]("Height: " + height + " meters");
[Link]("Is Student: " + isStudent);
[Link]("First Name: " + firstName);
[Link]("Full Name: " + fullName);
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 30


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Command Line Arguments

In Java, command line arguments provide a way to pass information to a program


when it is executed. These arguments are passed to the main method and are stored in an
array of String called args. This feature allows users to influence the behavior of the
program without changing its source code, making it more flexible and dynamic.

1. Understanding Command Line Arguments

Command line arguments are values passed to a Java program at the time of execution.
These values are supplied after the program's name when running the program from the
command line.

Main Method and args Array:

o The main method in Java is defined as public static void main(String[] args). The args
parameter is an array of String objects that stores the command line arguments.
o If the user provides multiple arguments, they are stored as separate elements in the
args array, with args[0] representing the first argument, args[1] the second, and so
on.

2. Example of Command Line Arguments

public class Main {


public static void main(String[] args) {
if ([Link] > 0) {
[Link]("First argument: " + args[0]);
} else {
[Link]("No arguments provided.");
}
}
}

Explanation:

o [Link]: This checks the length of the args array, which tells you how many
arguments were passed.
o args[0]: This accesses the first argument in the array. If at least one argument is
passed, it prints the first argument; otherwise, it prints a message saying no
arguments were provided.
3. How to Pass Command Line Arguments

Command Line Execution:

To run a Java program with command line arguments, you use the following syntax in the
command line (or terminal):

java Main argument1 argument2

CIC Sagi Rama Krishnam Raju Engineering College(A) 31


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

Example:

java Main Hello World

In this example:

▪ args[0] would be "Hello".


▪ args[1] would be "World".

Expected Output:

If you run java Main Hello, the output would be:

First argument: Hello

If you run java Main without any arguments, the output would be:

No arguments provided.

Method Overloading

Definition:

• Method overloading allows a class to have multiple methods with the same name,
but with different parameter lists.
• The parameters can differ in the number of parameters, their types, or both.
• The correct method to be executed is determined by the method signature (the
method name and parameter list).

Example:

class Calculator {
// Overloaded methods
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}

double add(double a, double b) {


return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](5, 10)); // Calls first method

CIC Sagi Rama Krishnam Raju Engineering College(A) 32


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

[Link]([Link](5, 10, 15)); // Calls second method


[Link]([Link](5.5, 10.5)); // Calls third method
}
}

Benefits:

• Improves code readability and usability by allowing the same method name to be
used for similar operations.
• Reduces the need for method names with different names for different tasks, making
the API easier to understand and use.

CONSTRUCTORS

In Java, a constructor is a special method that is used to initialize objects. The constructor
is called when an object of a class is created. It has the same name as the class and does not
have a return type. Constructors can be broadly categorized into the following types:

• Default Constructor
• Parameterized Constructor
• Copy Constructor

Let’s dive into each of these with detailed explanations and examples.

Default Constructor

A default constructor is a no-argument constructor that is automatically generated by the


Java compiler.

If no constructor is explicitly defined in a class, the compiler automatically provides a


default constructor.

This default constructor:

• Has no parameters.
• Initializes object fields with their default values (e.g., 0 for numeric types, null for
objects, false for boolean).
• Allows the creation of objects even if no custom constructor is provided.

Example:

class Car {
String model;
int year;

// Default constructor
Car() {
model = "Unknown";
year = 0;
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 33


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car(); // Calls the default constructor
[Link](); // Output: Model: Unknown, Year: 0
}
}

In this example, when car1 is created, the default constructor initializes the model to
"Unknown" and year to 0.

Parameterized Constructor

A parameterized constructor is a constructor that accepts arguments, allowing the user to


provide initial values to the object's attributes at the time of creation.

Example:

class Car {
String model;
int year;

// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}

void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car2 = new Car("Tesla", 2024); // Calls the parameterized constructor
[Link](); // Output: Model: Tesla, Year: 2024
}
}

In this example, when car2 is created, the parameterized constructor initializes the model
to "Tesla" and year to 2024.

Copy Constructor

A copy constructor is a special type of constructor used to create a new object as a copy of
an existing object. Java doesn’t provide a built-in copy constructor, but you can define one

CIC Sagi Rama Krishnam Raju Engineering College(A) 34


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

by passing an object of the same class to the constructor.

Example:

class Car {
String model;
int year;

// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}

// Copy constructor
Car(Car car) {
[Link] = [Link];
[Link] = [Link];
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car3 = new Car("Audi", 2022); // Calls the parameterized constructor
Car car4 = new Car(car3); // Calls the copy constructor
[Link](); // Output: Model: Audi, Year: 2022
}
}

Here, car4 is created as a copy of car3 using the copy constructor, and they have the same
values for model and year.

Constructor Overloading

Constructor overloading in Java allows a class to have more than one constructor with
different parameter lists. This enables the creation of objects in different ways.

Example:

class Car {
String model;
int year;

// Default constructor
Car() {
model = "Unknown";
year = 0;
}

CIC Sagi Rama Krishnam Raju Engineering College(A) 35


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
// Another parameterized constructor with only one parameter
Car(String m) {
model = m;
year = 2021; // Default year if not specified
}
void display() {
[Link]("Model: " + model + ", Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car car5 = new Car(); // Calls the default constructor
Car car6 = new Car("BMW", 2023); // Calls the parameterized constructor
Car car7 = new Car("Mercedes"); // Calls the overloaded constructor

[Link](); // Output: Model: Unknown, Year: 0


[Link](); // Output: Model: BMW, Year: 2023
[Link](); // Output: Model: Mercedes, Year: 2021
}
}

In this example, the Car class has three constructors: a default constructor, a two-parameter
constructor, and a one-parameter constructor, demonstrating constructor overloading.

this Keyword

The this keyword in Java is a reference to the current object. It is used to refer to instance
variables, invoke methods, or constructors of the current class.

Common Uses of this Keyword:

• To refer to the current class instance variable.


• To invoke the current class method (implicitly or explicitly).
• To invoke the current class constructor.

Example:

class Car {
String model;
int year;

// Parameterized constructor
Car(String model, int year) {
// Using 'this' keyword to refer to instance variables
[Link] = model;

CIC Sagi Rama Krishnam Raju Engineering College(A) 36


Object Oriented Programming Through JAVA[B23CS2103] Ch Raghuram & [Link]

[Link] = year;
}

// Another constructor that calls the parameterized constructor


Car(String model) {
this(model, 2021); // Calls the above constructor with default year
}

void display() {
[Link]("Model: " + [Link] + ", Year: " + [Link]);
}
}
public class Main {
public static void main(String[] args) {
Car car8 = new Car("Volvo", 2020); // Calls the parameterized constructor
[Link](); // Output: Model: Volvo, Year: 2020

Car car9 = new Car("Ford"); // Calls the constructor that uses 'this'
[Link](); // Output: Model: Ford, Year: 2021
}
}

In this example:

• The this keyword is used to differentiate between instance variables ([Link] and
[Link]) and constructor parameters (model and year).
• The second constructor demonstrates constructor chaining by invoking another
constructor using this().

Key Rules for Constructors in Java

• Constructors must have the same name as the class.


• Constructors do not have a return type, not even void.
• Constructors can use public, protected, private, or default (package-private) access
modifiers.
• Constructors can be overloaded with different parameter lists.
• The compiler provides a default constructor if none are defined.
• Constructors are called automatically when an object is created; this() can invoke
another constructor in the same class.
• Constructors can use this() to call another constructor in the same class; super()
calls the parent class's constructor.
• Constructors cannot be declared as abstract, static, final, or synchronized.
• Constructors are not inherited by subclasses; subclasses can call a superclass
constructor using super().
• Constructors cannot have an explicit return type.

***********

CIC Sagi Rama Krishnam Raju Engineering College(A) 37

You might also like