0% found this document useful (0 votes)
103 views113 pages

JAVA - MCA 2024 - UNIT 1-Student

Uploaded by

dajij82325
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)
103 views113 pages

JAVA - MCA 2024 - UNIT 1-Student

Uploaded by

dajij82325
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

23MCA1CC1-PROGRAMMING IN JAVA

UNIT I 15 hours
Java Buzzwords – Class Fundamentals – Declaring Objects – Introducing
Methods – Constructors – This keyword – Garbage Collection –
Overloading Methods – Argument Passing – Recursion – Access Control
Understanding static – final. Inheritance Basics – Using super – Method
overriding – Dynamic Method Dispatch – Using Abstract Classes – * Final
with Inheritance * – Object class.
An overview of Java or History of Java
1. Java is an object-oriented programming language developed by Sun Microsystems in 1991.
2. It was created by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan as part of a
research initiative known as the Green project.
3. Initially, James Gosling referred to it as "Greentalk."
4. The original design was intended for small, embedded systems in electronic devices like TVs, VCRs, freezers, and
washing machines.
5. However, this idea was abandoned due to technical challenges.
6. The language was later renamed "Oak" after the robust oak tree.
7. In 1995, Oak was renamed "Java" because "Oak" was already trademarked by Oak Technologies.
8. James Gosling named it "Java" after the Indonesian island known for its coffee, while he was drinking coffee near
his office.
9. Java is just a name and does not stand for anything.
10. The internet and the World Wide Web started to gain global popularity in 1995.
11. Sun Microsystems promoted Java as the internet programming language.
12. Java became popular as a web technology that adds dynamic functionality to web pages.
13. In January 2010, Oracle acquired Sun Microsystems, and since then, Oracle has been responsible for
maintaining and distributing Java.
The Evolution of Java or Java’s Lineage

✓ In the history of computer languages, it will be noted that B


led to C, C evolved into C++, and C++ paved the way for Java.
✓ Java is linked to C++, which originates from C.
✓ Java inherits its syntax from C, and many of its object-oriented
features are influenced by C++.

✓ B → C → C++ → Java
Features of Java or JAVA BUZZ WORDS
Sun described Java as
"A simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable,
high-performance, multi-threaded and dynamic language.“
1. Simple
2. Object-oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-neutral
8. Portable
9. High performance
10. Multithreaded
11. Dynamic
1.Simple
✓ Java was designed such that it is easy for the programmer to learn and use.
✓ It inherits syntax from C and OOPs concept from C++, so it is very easy to learn if programmer knows
C and C++.
✓ Java technology has eliminated complex features like Operator overloading, Multiple inheritance,
pointers.
2.Object Oriented
✓ Everything in Java is an object. It provides the features of abstraction, encapsulation, inheritance and
polymorphism.
✓ Anything in Java is embedded into a class.
✓ Almost all data types are objects.
3. Distributed
✓ Distributed applications run on multiple computers and communicate over a network.
✓ Java supports creating such applications, allowing programs on one machine to easily access
resources (files, Java objects, etc.) on another machine over the internet.
✓ Java offers a comprehensive set of libraries for network programming, including support for
Remote Method Invocation (RMI) and protocols like TCP/IP and UDP.
4.Compiled and Interpreted
✓ Java is compiled as well as interpreted programming language.
✓ Java source code is compiled into bytecode, which is a low-level, platform-independent
representation of the code.
✓ The bytecode is machine-independent and can run on any machine that has a Java interpreter,
which is part of the Java Virtual Machine (JVM).
5.Robust
✓ Robustness refers to reliability.
✓ Java is considered robust because it employs strong memory management with automatic
garbage collection.
✓ It features an exception handling mechanism to manage errors and unexpected situations
gracefully.
✓ Java includes built-in type checking that verifies code both at compile time and runtime.

6.Secure
Java implements various security mechanisms to protect your system from harmful
programs.
✓ It is secure because it has eliminated the concept of pointers.
✓ Java includes a dedicated security manager in the JVM to handle application security
needs.
✓ It features a Bytecode Verifier that checks code fragments for illegal code.
✓ Java's security mechanisms are designed to be difficult to breach.
7.Architecture-neutral/Platform Independent
✓ Java is designed to be independent of specific hardware or operating systems.
✓ It achieves this through the concept of bytecode.
✓ Bytecode allows a Java application to run on any hardware and operating system.
✓ This platform independence enables Java to follow the WORA (Write Once, Run
Anywhere) principle.
✓ Essentially, Java's .class files can execute seamlessly across various operating
systems.
8.Portable
✓ Portability in programming means a program compiled on one machine can run on
any machine worldwide without changes.
✓ Java programs exemplify portability because they can move between different
architectures, hardware configurations, operating systems, and system setups
seamlessly.
✓ This inherent portability makes Java an ideal choice for applications that need to run
across diverse environments without requiring modifications.
9.High Performance
✓ Java code is compiled into bytecode for the JVM.
✓ The JVM dynamically translates frequently used bytecode into machine code using JIT
compilation, improving performance.
✓ Java efficiently executes code with the help of bytecode and JIT compilation.
✓ Standard libraries in Java provide optimized data structures and algorithms, further
enhancing performance.
✓ The JIT compiler, part of the JVM by Sun Microsystems, speeds up Java program
interpretation by compiling bytecode on-the-fly.
✓ It stores optimized machine code for future execution without requiring recompilation.
✓ Sun's Java HotSpot Performance Engine includes a compiler that optimizes frequently
used code segments, significantly boosting overall Java program performance.
10.Multithreaded
✓ Multithreading allows multiple threads to run concurrently within the same process.
✓ Each thread operates independently and can share memory with other threads.
✓ It facilitates parallel execution of different parts of a program, optimizing CPU usage.
✓ Java applications can perform multiple tasks simultaneously using separate threads,
avoiding the need to wait for one task to finish before starting another.
✓ For example, applications like Microsoft Word utilize multithreading for tasks such as
typing, spell check, grammar check, auto-save, and autocomplete, enhancing user
productivity and efficiency.
11. Dynamic
✓ Java compiles source code into .class files.
✓ These .class files are dynamically loaded into memory at runtime.
✓ Java applications utilize runtime libraries and resources during execution.
✓ Java can leverage efficient functions from C/C++.
✓ Installing a new version of a library automatically updates all programs that use it.
Types of Java programs
1. An application program is a software program that is designed to perform specific tasks on a local
computer, such as processing data, reading and writing files, or solving equations

2. An applet is a small Java program that is designed to run within a web browser and add
interactivity to web pages. It runs in a web browser and works on the client-side
Note: Oracle has announced that Applets are deprecated in JDK 9 and will be removed from the JDK
in the future.

3. A servlet is a Java program that runs on a web server and works on the server-side to process HTTP
requests and generate dynamic web content.

Note:
✓ Application Program –Executed by the Java interpreter.
✓ Applet- Java enabled web browser.
✓ Servlet- web server
How a Java application program works
1. Write Java code: Java application programs are written using a text editor or an integrated
development environment (IDE) such as Eclipse, NetBeans etc.
2. Compile Java code: The Java source code is compiled into bytecode using the Java compiler called
“javac”
3. Run the Java application: The compiled program can now be executed by the JVM using the "java"
command followed by the name of the main class in the program.
Hardware and
Programmer
Operating System

Source Code Byte Code

Text Editor Compiler Interpreter


.java file .class file
Notepad, javac java
emacs,vi appletviewer
netscape
simple java program
/*This is a simple java program*/
class Sample
{
public static void main (String args[])
{
System.out.println (“This is a simple Java program”);
}
}
class Sample: This line declares a new class named Sample. In Java,
every program must have at least one class definition.
Every class definition in Java must begin with “{“ and ends with “}”.
Simple Java Program-Some important points
✓ public: This is an access specifier, which means that this method is accessible
from anywhere.
✓ static: This means that the method can be called without creating an instance
of the class.
✓ void: This indicates that the method does not return any value.
✓ main: This is the name of the method. The Java runtime environment looks for
the main method to start the execution of an application.
✓ String args[]: This is an array of String objects that stores command-line
arguments passed to the program. Java is case sensitive.
System: This is a predefined class in Java that provides standard input,
output, and error streams
Out: out is a static data member of the System class, used for output purposes,
specifically for writing to the console.
println() : This is a method of PrintStream that prints a line of text to the console.
Single-File Source-Code Programs in Java 11 +
✓In Java, a single-file source-code program is one where all the
code, including classes, methods, and statements, is contained
in a single file with a .java extension.
Compiling and Running a java single-file program before and after java 11
✓ A single-file program is one where the program fits in a single source file.
✓ This means that all the code needed to run the program is contained within a
single file, including the main method.
✓ Before Java 11, running a Java program, even a single source file, required two
steps:
1. Compiling: Use the Java compiler (javac) to convert the source code into
bytecode.
Example: To compile MyFile.java, use:
javac MyFile.java

2. Running: Use the JVM (java command) to execute the compiled bytecode.
Example: To run the compiled MyFile.class, use:
java MyFile
✓ There are no restrictions on the number of classes in the file.
Starting with Java 11, you can run a single-file source code program
without needing to compile it first.
This feature simplifies the development process, especially for small
programs
Writing a Single-File Source Code Program
1. Create a Java file: Write your Java code in a file with a .java
extension.
2. Run the Java file: Use the java command followed by the
filename(with the .java extension) to run the program.
✓ For example, to run a file named "Hello.java", we would run the
command "java Hello.java“
Note: In Java 11, you can still use the traditional method of compiling
with javac and running with java:
Execute Java single file program Without Compilation – Example:
class Welcome {
public static void main(String[] args) {
System.out.println(" Welcome to Java" );
System.out.println(" This code runs without needing to be compiled beforehand");
System.out.println(" Java version is " + System.getProperty("java.version"));
}
}
I:\Java11>java Welcome.java
Welcome to Java
This code runs without needing to be compiled beforehand
Java version is 16.0.1
Example 2
// Define a class named HelloWorld
class HelloWorld {
// Define a method named greet
public void greet() {
System.out.println("Hello, World!");
}
// Define the main method in the same class
public static void main(String[] args) {
// Create an object of the HelloWorld class
HelloWorld obj = new HelloWorld();
// Call the greet method using the object
obj.greet();
}
}

Output
I:\Java11>java HelloWorld.java
Hello, World!
Console Input or Keyboard Input (interactive input)
• In Java, input from the keyboard is obtained via the standard input
stream, represented by System.in.
• Java provides classes in the java.io package for input/output operations
and exception handling.

• There are a number of ways to take input from keyboard.


1. BufferedReader and InputStreamReader: These classes can read
input character-by-character or line-by-line from System.in.
2. Scanner Class: Specifically designed for parsing input into tokens (like
integers, doubles) from System.in.
3. Commandline Arguments: Inputs provided directly when launching a
Java program via command-line arguments.
1. USING BufferedReader and InputStreamReader classes
By wrapping the System.in (standard input stream) in an InputStreamReader which is
wrapped in a BufferedReader, we can read input from the user in the command
line.

We may also give values to variables interactively through the keyboard using the read() or
readLine() method.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
Byte b=Byte.parseByte(br.readLine());
short s= Short.parseShort(br.readLine());
int i=Integer.parseInt(br.readLine());
long l=Long.parseLong(br.readLine());
float f=Float.parseFloat(br.readLine());
double d=Double.parseDouble(br.readLine());
char c = (char) br.read();
Reading Characters Reading Strings
To read string we have to use readLine()
read() method is used with BufferedReader
function with BufferedReader class's object.
object to read characters. As this function
returns integer type value has we need to
Example 2. Read a String
use typecasting to convert it into char
// Program to get & display your name
type.
// Illustrates Interactive input
Example 1. Read a Character import java.io.*;
import java.io.*; class dispname
class readchar{ {
public static void main(String args[ ]) throws public static void main(String args[])
IOException { throws IOException
{ BufferedReader br = new
char c; BufferedReader( new
BufferedReader br=new BufferedReader(new InputStreamReader(System.in) );
InputStreamReader(System.in)); System.out.println("Enter your name :");
c = (char) br.read(); //Reading character String name = br.readLine();
System.out.println(c); System.out.println("\nYour name is " +
name);
}
}
} }
Example 3:Conversion of strings to numbers
// Program to add two numbers
// Illustrates Conversion of strings to numbers
import java.io.*;
class Add
{
public static void main(String args[]) throws IOException
{
int a,b,c;
BufferedReader br = new BufferedReader( new
InputStreamReader(System.in) );
System.out.print("Enter the first number ");
a = Integer.parseInt( br.readLine() );
System.out.print("Enter the second number ");
b = Integer.parseInt(br.readLine());
c = a+b;
System.out.println("Result of addition = " + c);
}
}
2.Using Scanner Class
✓ Prior to Java 1.5, obtaining input from the console involved several steps.
✓ However, with the introduction of the Scanner class in Java 1.5, this process has been greatly simplified.
✓ The java.util package provides the Scanner class, which facilitates reading input from various sources, including the
keyboard.
✓ To utilize the Scanner class in a Java program, it needs to be imported:
import java.util.Scanner;
Next, create an instance of the Scanner class to read input from the standard input stream (i.e., the console).
The basic syntax for this is:
Scanner sc = new Scanner(System.in);
✓ This creates a new Scanner object called "sc" that reads input from the standard input stream (i.e. the console).
✓ This line initializes a new Scanner object named sc, which reads input from the console.

The Scanner class offers methods to read different types of input, such as strings, integers, doubles, and booleans,
making it a versatile tool for handling user input in Java applications.
Example:
Scanner sc = new Scanner (System.in);
int i = sc.nextInt();
System.out.println("You entered " + i);
✓ This example reads a single int from System.in and outputs it to System.out. It does not check that the user actually
entered an int.
commonly used Methods of the Scanner class
Method Description

nextBoolean() Reads a Boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

Note: The import java.io.*; statement is not necessary for using the Scanner class for input operations.
Only import java.util.Scanner; is required.
Scanner class example
The Scanner Class can be used as an alternative to the Buffered Reader, used in traditional Java.
//finding area and perimeter of the circle
import java.util.Scanner;
class Find {
public static void main(String[] args) {
double area, perimeter, radius;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Radius: ");
radius = sc.nextDouble();
perimeter = 2 * Math.PI * radius;
area = Math.PI * Math.pow(radius, 2);
System.out.printf("Perimeter\t: %f\n", perimeter);
System.out.printf("Area\t\t: %f\n", area);
sc.close();
}
}
Enter the Radius: 23
Perimeter : 144.513262
Area : 1661.902514
3.Using Command Line Arguments
✓ Command line arguments in Java are values or data passed to a Java program during its execution
from the command line.
✓ These arguments are stored in a string array, args, which is passed to the program's main() method.
✓ This array is declared as a parameter in the main() method.
✓ Command line arguments allow input data to be supplied at runtime, rather than being hardcoded
into the program.
✓ A Java application can accept any number of arguments(Stings) from the command line.
✓ Users enter these arguments after the class name when invoking the application.

✓ The args.length property returns the number of command line arguments provided.
Program1 Program2
public class Num1 {
// Display all command-line arguments. public static void main(String[] args) {
class CommandLine { if (args.length < 2) {
public static void main(String[] args) { System.out.println("Please enter two numbers as command line
for (int i = 0; i < args.length; i++) { arguments.");
return;
System.out.println("args[" + i + "]: " + }
args[i]); int a = Integer.parseInt(args[0]);
} int b = Integer.parseInt(args[1]);
} System.out.println("Entered numbers are: " + a + " " + b);
}
// Swap the numbers without using a third variable
a = a + b;
b = a - b;
Output a = a - b;
java CommandLine.java jama mohamed System.out.println("Numbers after exchange: " + a + " " + b);
college trichy }
args[0]: jama }
args[1]: mohamed java Num1.java 25 45
args[2]: college Entered numbers are: 25 45
args[3]: trichy
Numbers after exchange: 45 25
console output or screen output
1.System.out.print(); This method prints the specified text to
✓ In Java, output to the standard output (screen) is managed
the console without a newline character at the end.
through System.out, an instance of the PrintStream class that
represents the standard output stream. Syntax: System.out.print("text");
✓ This functionality is provided by the System class within the Example:
java.lang package. System.out.print("Hello, ");
System Class: Within java.lang, the System class includes a System.out.print("world!");
static variable out, which is of type PrintStream. Output: Hello, world!
Accessing System.out: Because out is static, it can be accessed 2.System.out.println(); This method prints the specified text to
directly using System.out. the console with a newline character at the end
Output Methods: Methods like print(), println(), and printf() Syntax: System.out.println("text");
from the PrintStream class facilitate printing data to the console, Example1:
supporting both plain and formatted output.
System.out.println("Hello, ");
1. System.out.println("text"): Prints the text followed by a
System.out.println("world!");
newline character.
Hello, world!
2. System.out.print("text"): Prints the text without appending
a newline character.
3. Formatting Output: Use System.out.printf() for 2.System.out.println(); // Write a blank line
formatted output using format specifiers (%s, %d, %f, etc.).
3.System.out.printf(); public class PrintfExample {
public static void main(String[] args) {
✓ The printf() method in Java, introduced in JDK 5.0, is
String name = "Raja";
indeed similar to the printf() function in C.
int age = 30;
✓ The printf() method in Java enhances the capabilities
double salary = 2500.75;
of standard output, providing a powerful tool for
// Using printf to format output
formatted text output, similar to its counterpart in
System.out.printf("Name: %s, Age: %d, Salary: %.2f\n",
the C programming language.
name, age, salary);
Syntax: System.out.printf("format", arg1, arg2, ...); // More examples
The format string can contain placeholders that start with int number = 123456789;
%. The placeholders are replaced with the corresponding System.out.printf("Formatted number with commas: %,d\n",
arguments. number);
output double pi = Math.PI;
java PrintfExample.java System.out.printf("Pi value: %.4f\n", pi);
Name: Raja, Age: 30, Salary: 2500.75 // Formatting dates
Formatted number with commas: 123,456,789 int day = 4, month = 7, year = 2024;
System.out.printf("Date: %02d-%02d-%d\n", day, month,
Pi value: 3.1416
year);
Date: 04-07-2024 }
}
Formatting Numeric Output using the System.out.printf( ) Method

Here are some of the most commonly used format specifiers in System.out.printf():
1. %d - Format as a decimal integers such as byte, int, short, long.
2. %f - Format as a floating-point number
3. %s - Format as a string
4. %c - Format as a character
5. %b - Format as a Boolean value (true or false)
6. %t - Format as a date/time value
7. %e - Format as a scientific notation
8. %x - Format as a hexadecimal integer
9. %o - Format as an octal integer
Note:
1. The output of a printf statement is right-justified by default.
2. To force the output to be left-justified, you can use the format specifier flag. If flag is set to ‘-’
(negative), then the output of the result is left justified.
3. System.out.printf( ) does not print a newline character by default – it is similar to System.out.print( ). Include %n
in the format string to do this.
Example: double pi = Math.PI;
System.out.printf("Pi value: %.4f%n", pi);
Introducing Classes
Class Fundamentals
✓ A class in Java defines a new data type. For example, a class like Box introduces a new
type named Box.
✓ A class consists of data variables (properties) and methods (code) that manipulate those
data.
✓ It serves as a blueprint or template for creating objects.
✓ An object is a specific instance of a class.
✓ When creating an object, a specific instance of that class is generated with its unique set
of values for properties.
✓ The purpose of a class is to describe an object.
✓ (ie) A class is a description of an object, and an object is an instance of a class.
✓ Classes form the foundation of object-oriented programming (OOP).
✓ In Java, classes are fundamental; every program must use at least one class.
✓ A java program is defined by using one or more classes
class classname {
The General Form of a Class
type instance-variable1; ✓Variables defined within a class are called instance variables.
type instance-variable2; ✓The code within a class is contained within methods, which
// ... define its behavior.
type instance-variableN;
✓Variables defined within a class are called instance variables
type methodname1(parameter-list)
{
because each instance of the class (that is, each object of the
// body of method class ) contains its own copy of these variables.
} ✓Collectively, the methods and variables defined within a class
type methodname2(parameter-list) are called members of a class
{ ✓The words Object and Instance are often used interchangeably.
// body of method
} Attributes And Behavior
// ... ✓A Java class consists of two types of information: attributes and
type methodnameN(parameter-list) behavior
{ ✓A class defines the properties and behaviors for the objects.
// body of method
Attributes: These are properties defined by variables in the class.
}
}
Behavior: Also known as operations, these are defined using
methods in the class.
Introducing Methods
Classes usually consist of two things:
•instance variables and
•Methods.
A Java method is sequence of statements that carry out specific task
General form of a method definition:
datatype methodname (parameter-list) Example:
{ double volume(double w, double h,
// method body double d)
{ return w*h*d;
}
}
✓ datatype specifies the type of data returned by the method. This can be any valid types
including class types. If method does not return any value, return type is void.
✓ methodname must be a legal identifier other than those already declared for other items
within the current scope.
✓ paramter-list is the sequence of type and identifier pairs separated by commas. If no
parameters are present, paramter-list can be empty.
✓ Methods having return type other than void, must have a return statement to return a value.
Example 1:
Examples Example 3
class Box { class Account
double width; {
double height; double balance;
void deposit( double amount )
double depth;
{
// display volume of a box balance += amount;
void volume() { }
System.out.print("Volume is ");
System.out.println(width * height * depth); double withdraw( double amount )
} {
} if (balance >= amount)
{
Note: A class defines a new type of data. In this case, the balance -= amount;
new type is called Box.
return amount;
Example 2: }
class Rectangle else
{ int length, width; return 0.0;
}
int area() double getbalance()
{ {
return length *width; return balance;
} }
}
int perimeter()
{ return 2*(lenth+width);
}
}
Creating Objects in Java
✓ Objects in Java are created dynamically using the new operator.
✓ This process is known as instantiation.
Syntax:
ClassName objectName; // Declare a reference variable of type ClassName
objectName = new ClassName(); // Allocate memory and create an object of ClassName
// OR
ClassName objectName = new ClassName(); // Combine declaration and instantiation
Explanation
ClassName: Replace ClassName with the actual name of the class you want to instantiate.
objectName: This is the name of the reference variable that will refer to the object.
new: The new keyword dynamically allocates memory for an object of ClassName.
(); Parentheses after ClassName can include arguments if the class has a constructor that accepts
parameters.
Creating Objects
Example:
Box myBox = new Box(); creates a new object of the Box class and assigns it to
the reference variable myBox.
Box: This is the class name from which a new object is being created.
myBox: This is the reference variable that will hold the memory address of the
newly created Box object.
new: This keyword is used to allocate memory and create a new instance (object)
of the Box class.
Box(): This is the constructor of the Box class. It initializes the new object. In this
case, with no arguments provided (()), it invokes a default constructor that
initializes a default Box object.
Accessing Object Members
✓ In Java, we can access the members (variables and methods) of an object using the dot (.) operator.
Objectname.varibale name;
Objectname.methodname (parameter – list)
• Ex:
1) Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
vol = mybox1.volume( );

2)Rectangle r1 = new Rectangle();


r1.length = 10;
r1. Width=20;
r1.area();
r1.perimeter();
Objects VS references
Object: class Box {
int width;
✓ An instance of a class with state (data) int height;
int depth;
and behavior (methods).
✓ Objects are created at runtime using the int volume() {
return width * height * depth;
new keyword }
Reference: }
class Boxexample {
✓ A reference is a variable that stores the public static void main(String[] args) {
memory address of an object. Box myBox = new Box(); // `myBox` is a reference to a `Box` object.
System.out.println("Reference" + myBox); //
✓ It acts like a pointer, giving you a way to myBox.width = 10; // Accessing the object's fields through the reference.
access the object's data and methods. myBox.height = 20;
myBox.depth = 15;
Note:
When we attempt to print the value of a int vol = myBox.volume(); // Calling the object's method through the
reference variable, the output contains the reference.
System.out.println("Volume: " + vol); // Output: Volume: 3000
name of the class which has been instantiated }
concatenated by @ and the hash code }
created for it by Java
I:\javaprogram 2024>javac Boxexample.java
I:\javaprogram 2024>java Boxexample
ReferenceBox@23fc625e
Volume: 3000
Constructors
✓ Constructors are special methods that are used to initialize objects when they are
created.
✓ Constructors have the same name as the class name , and they have no return type
(not even void).
✓ If a constructor is not defined explicitly in a class, Java provides a default constructor
with no arguments.
✓ When an object is created using the new keyword, the constructor of the class is called
automatically to initialize the object's instance variables.
Constructors
There are two types of constructors:
1.Default constructor (no-arg constructor) 2.Parameterized constructor
A constructor that has parameter is known as
✓ When a class is created without a constructor, the
parameterized constructor.
compiler generates a default constructor.
Syntax
✓ This default constructor is public, has no ClassName(ParameterList)
parameters, and performs no actions. { //constructor body
}

Rectangle(int length, int width)


{
//constructor body
}
Examples: Constructors
1) 3) class Account
class Box { {
double width;
double height; double balance;
double depth;
Box() // constructor // Constructor to initialize balance
{
System.out.println("Constructing Box");
public Account( double amount )
width = 10; height = 10; depth = 10; {
} balance = amount;
}
2)
class Rectangle
{
int length, width;// instance variables
Rectangle(int a, int b)
// parameterized constructors
{ length = a;
Width = b;
}
Differences between a constructor and a method

Constructors Methods
1. A constructor is used to initialize the instance 1. A method is used for any general purpose
variables of a class. processing or calculations.
2. A constructor’s name and class name should 2. A method has a unique name that identifies
be same. behavior
3. A constructor is called at the time of creating 3. A method can be called after creating the object.
object. 4. A method can be called several times on the
4. A constructor is called only once per object. object.
Complete Examples
// Class definition //Main class – A class contains the main() method

class Box { class BoxDemo {


public static void main(String args[]) {
double width;
Box mybox1 = new Box(10, 20, 15);
double height;
Box mybox2 = new Box(3, 6, 9);
double depth;
double vol;
Box(double w, double h, double d) { vol = mybox1.volume();
width = w; height = h; depth = d; System.out.println("Volume is " + vol);
} vol = mybox2.volume();
double volume() { System.out.println("Volume is " + vol);
return width * height * depth; }
} }
} Output
Volume is 3000.0
Volume is 162.0
Example 2
class Rectangle // class definition
class Rectdemo // Main class
{ { public static void main( String args[])
int length, width;// instance { Rectangle r1= new Rectangle(10,5);
variables System.out.println("Area of Rectangle= "+r1.area());
Rectangle(int a, int b) // constructor System.out.println("Perimeter of Rectangle=
"+r1.perimeter());
{ length = a;
Rectangle r2= new Rectangle(11,8);
width = b; System.out.println("Area of 2nd Rectangle= "+r2.area());
} System.out.println("Perimeter of 2nd Rectangle=
int area() // Method "+r2.perimeter());
}
{
}
return length *width; Output
} Area of Rectangle = 50
int perimeter() // method Perimeter of Rectangle = 30
{ return 2*(length+width); Area of 2nd Rectangle= 88
Perimeter of 2nd Rectangle= 38
}
}
class BankAccount {
Example 3 class MainBank {
public static void main(String[] args) {
String accountNumber;
BankAccount account = new BankAccount("123456789", 1000.0);
double balance;
// constructor
System.out.println("Account number: " + account.getAccountNumber());
BankAccount(String accountNum, double initialBalance) {
System.out.println("Balance: " + account.getBalance());
accountNumber = accountNum;
balance = initialBalance;
account.deposit(500.0);
}
System.out.println("New balance after deposit: " + account.getBalance());

String getAccountNumber() {
account.withdraw(200.0);
return accountNumber;
System.out.println("New balance after withdrawal: " +
} account.getBalance());
double getBalance() { }
return balance; }
} output
void deposit(double amount) { I:\Java11>java MainBank
balance += amount; Account number: 123456789
} Balance: 1000.0
void withdraw(double amount) { New balance after deposit: 1500.0
balance -= amount; New balance after withdrawal: 1300.0
}
}
The this keyword
✓ In Java, the this keyword is a reference variable that refers to the current object
✓ The this keyword in Java is particularly useful within methods and constructors to refer to
and access the object's own members, such as fields (variables) and methods.
To Refer to Instance Variables: When a method parameter has the same name as an instance
variable, this helps differentiate between them.
Instance Variable Hiding:

✓ The this keyword in Java is commonly used to distinguish between instance variables (fields
of a class) and formal variables (parameters declared in methods) when they share the same
name.
Note: Static methods, or class methods, do not have a this reference
//Example 1: instance and formal variables are different
class Box {
double w = 5, h = 5, d = 5; // instance variables
// Constructor with formal parameters w1, h1, d1
Box(double w1, double h1, double d1) {
// Assigning values from formal parameters to instance variables
w = w1;
h = h1;
d = d1;
}
// Method to calculate volume based on instance variables w, h, d
double volume() {
return w * h * d;
} Output:
}
class BoxTest1 {
Volume is:6.0
public static void main(String args[]) {
// Creating an instance of Box with dimensions 1x2x3
Box b = new Box(1, 2, 3);
// Printing the calculated volume
System.out.println("Volume is: " + b.volume());
}
}
// Example 2: instance and formal variables are same
class Box{
double w=5,h=5,d=5; // instance variables with default values
// Constructor with parameters having the same names as instance variables
Box(double w,double h,double d){
w=w; When a formal variable has the
h=h;
d=d; same name as an instance variable,
} the formal variable hides the
double volume(){ instance variable.
return w*h*d;
} Output:
}
class BoxTest2{
Volume is:125.0
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
//Example 3: ’this’ hides the instance variables
class Box{
double w=5,h=5,d=5; // instance variables with default values
// Constructor with parameters having the same names as instance variables
Box(double w,double h,double d){
this.w=w;
this.h=h; this can be used to resolve any name
this.d=d; collisions that might occur between
}
instance variables and formal variables.
double volume(){
return w*h*d;
} Output:
}
class BoxTest2{
Volume is:6.0
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Garbage Collection
✓ Garbage in Java refers to objects that are no longer reachable or used by the program.

✓ Garbage collection is the automatic process where the Java Virtual Machine (JVM) reclaims memory
occupied by unreferenced objects, making it available for new objects.

✓ Unlike languages such as C++, where dynamically allocated memory must be manually released using delete,
Java automatically handles memory deallocation through its garbage collector.

✓ Objects in Java are automatically destroyed by the garbage collector when they are no longer referenced by
any variable in the program, eliminating the need for explicit destruction as in C++.

✓ The garbage collector is an integral part of the Java Runtime Environment (JRE), ensuring efficient memory
management.
✓ Garbage collection occurs periodically during the execution of a Java program to optimize memory usage
and performance. It is triggered primarily when the JVM detects a shortage of available memory.

✓ Although Java provides System.gc() as a method to suggest garbage collection, its actual invocation and
timing are JVM-specific and do not guarantee immediate destruction of unreferenced objects.
In java, there are three ways in which the references to an object can be released to make it eligible for Garbage Collection.
(ie) Objects can be unreferenced in three different ways
1. By anonymous object: Anonymous Object: Anonymous objects in Java are created without assigning them to any
reference variable. They are typically used for immediate method invocation or initialization without retaining access to
the object afterward.
new Student(); // Creates an anonymous Student object
After creation, an anonymous object cannot be accessed again because it lacks a reference variable. Despite this, it
occupies memory until eligible for garbage collection.
2. Null Reference: When a reference variable is assigned null, it releases its association with the object it previously
referenced. This action marks the object as unreferenced and available for garbage collection.
Student s = new Student();
s = null; // Releases the reference to the Student object
Here, s no longer points to any object (null), allowing the previously referenced Student object to be considered for
garbage collection.
3.Assigning a Reference to Another Object: When one reference variable is assigned to another, the original object
referenced by the first variable becomes unreachable if no other references exist to it.
Student s1 = new Student();
Student s2 = new Student();
s1 = s2;
After s1 = s2;, the original object referenced by s1 becomes unreachable and can be considered for garbage collection if no
other references exist to it.
Examples
1. class GarbageCollectionDemo {
public static void main(String args[]) {
Integer i = new Integer(5); 2. class GarbageCollectionExample {
System.out.println(i); public static void main(String[] args) {
i = new Integer(6); // Create two objects
System.out.println("Integer(5) can be recycled."); String s1 = new String("Hello");
System.out.println(i); String s2 = new String("World");
} // Set s1 to null
} s1 = null;
//s1 to null to indicate that we are no longer using this object.
J:\>java GarbageCollectionDemo // Call garbage collector
5 System.gc();
Integer(5) can be recycled. // Print the value of s2
6 System.out.println("s2 value: " + s2);
Note: }
The Integer object created with a value of 5 can be }
garbage collected because it is no longer referenced by
any active part of the program after the i reference
variable is reassigned to a new Integer object with a
value of 6.
finalize( ) method
✓ In Java, garbage collection automatically frees memory used by objects but does not manage non-Java resources
such as files, network connections, or database connections.
✓ To clean up such resources before an object is destroyed, you can define a finalize() method in the object's class.
✓ This method is called by the JVM before garbage collection to perform cleanup tasks.
✓ Finalize() is a method of the object class that can be invoked/called every time before the object is garbage
collected and the purpose of finalize() method is to perform cleanup processing.

protected void finalize( ){


// finalization code here
}

1. protected is a specifier in Java that restricts access to the finalize() method only within its class or subclasses

2. Programmers have no control over when or if the finalize() method will be invoked by the garbage collector

3. The finalize() method can lead to significant performance penalties. Due to these issues, it has been deprecated
since Java 9 and should be used cautiously when necessary.

4. Instead of relying on finalize(), Java developers are advised to use try-with-resources statements or implement the
AutoCloseable interface to properly manage resources. These modern approaches offer more predictable and efficient
resource cleanup mechanisms.
Overloading Methods
✓In Java, it's possible to define multiple methods within the same class that share the same
name but have different parameter declarations.
✓This practice is called method overloading and is a way Java implements polymorphism.
✓When methods are overloaded, Java determines which version to execute based on the
type and/or number of arguments provided during the method call.
✓Unlike the return type, which can vary between overloaded methods, Java solely relies on
the arguments to differentiate between them.

✓When invoking an overloaded method, Java selects the version whose parameters match
the arguments passed in the call.
✓This flexibility allows developers to create methods with the same name that operate
differently based on the inputs provided, enhancing code versatility and readability.
// Class FunctionOverload demonstrating method overloading
Example
class FunctionOverload {
// Main class Overloading to demonstrate method overloading
// Method to add two integers
class Overloading {
void add(int a, int b) {
public static void main(String args[]) {
int sum = a + b;
// Creating an instance of FunctionOverload class
System.out.println("Sum of a + b is " + sum);
FunctionOverload obj = new FunctionOverload();
}
// Method to add three integers
// Calling different overloaded methods with various
void add(int a, int b, int c) {
arguments
int sum = a + b + c;
obj.add(1, 2); // Calls add(int a, int b)
System.out.println("Sum of a + b + c is " + sum);
obj.add(45, 22, 33); // Calls add(int a, int b, int c)
}
obj.add(11.5, 22.5); // Calls add(double a, double b)
// Method to add two double variables
obj.add("Welcome", " to Java"); // Calls add(String s1,
void add(double a, double b) { String s2)
double sum = a + b; }
System.out.println("Sum of a + b is " + sum); }
} I:\javaprogram 2024>javac Overloading.java
// Method to concatenate two strings I:\javaprogram 2024>java Overloading
Sum of a + b is 3
void add(String s1, String s2) { Sum of a + b + c is 100
String s = s1 + s2; Sum of a + b is 34.0
System.out.println("Concatenation of two strings: " + s); Concatenation of two strings: Welcome to Java
Constructor overloading

✓ Similar to methods, constructors can be overloaded.


✓ Constructor overloading in Java allows a class to have multiple
constructors with different parameter lists.
✓ The compiler distinguishes between these constructors based
on the number and types of parameters.
Example
// Illustrates Classes - constructor overloading
public static void main(String[] args) {
class Student { // Creating Student objects using different
String name; constructors
int age; Student student1 = new Student("John",
20);
// Constructor with name and age parameters Student student2 = new Student("Ram");
Student(String name, int age) {
this.name = name; // Displaying student details
this.age = age; student1.display(); // Outputs: Name:
} John, Age: 20
student2.display(); // Outputs: Name:
Ram, Age: 0
// Constructor with only name parameter (age defaults to 0)
}
Student(String name) {
}
this.name = name;
this.age = 0; I:\javaprogram 2024>javac Student.java
} I:\javaprogram 2024>java Student
Name: John, Age: 20
// Method to display student details Name: Ram, Age: 0
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
Using Objects as Parameters
✓ n Java, you can pass objects as parameters to methods.
✓ This allows you to send complex data to methods and manipulate object properties within those methods.
class Test { int a, b; // Declare two integer variables
Test(int i, int j) / /Constructor with two parameters to initialize 'a' and 'b'
{
a = i; b = j;
}
// Method to compare two Test objects
boolean equals(Test o) // To receive an object use object type as a parameter like for an integer type use int type for parameter
{ if(o.a == a && o.b == b) return true; // Compare the invoking object (e.g., ob1) with the one that is passed (e.g., ob2)
else return false;
}
}
This program generates the
class PassOb {
following output:
public static void main(String args[])
ob1 == ob2: true
{Test ob1 = new Test(100, 22);
ob1 == ob3: false
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2)); // Pass an object ob2 to equals method()
System.out.println("ob1 == ob3: " + ob1.equals(ob3)); // pass an object ob3 to equals method()
}
Argument (Parameter) Passing in Java
✓ In Java, all parameters are passed by value, including object references.
✓ This means that for both primitive types and objects, what is passed to the method is a copy of the
variable.
However, the key difference lies in what is being copied:
1. Primitive Types:
When you pass a primitive type to a method, a copy of the actual value is passed.
Changes to the parameter within the method do not affect the original variable.
2. Object References:
✓ When you pass an object to a method, a copy of the reference to the object is passed, not the object
itself.
✓ While the reference itself is passed by value, it still points to the same object.
✓ Therefore, changes made to the object through this reference within the method will affect the
original object.
Note:
In Java, primitive types (such as int, double, etc.) are passed by value but objects are passed-by-reference.
Pass by Value
When a simple type is passed, it is passed by value
class Test1
{
public static void main (String args[])
{
Test ob=new Test(); Output:
int a=14, b=20;
System.out.println ("Before call:"+a+" " +b);
ob.set(a,b); I:\Java11>java Test1.java
System.out.println ("After call:"+a+" " + b); Before call:14 20
Within the method:28 10
} After call:14 20
}
class Test
{
void set (int i, int j)
{
i= i*2;
j = j/2;
System.out.println ("Within the method:"+i+" " + j);
}
}
Pass by Reference
When an object is passed to a method, it is passed by reference.
class Test2 {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 14; Output:
ob.b = 20;

System.out.println("Before call: " + ob.a + " " + ob.b); I:\javaprogram 2024>java Test2.java
// Call the method, which modifies the object Before call: 14 20
ob.set(ob); Within the method: 28 10
System.out.println("After call: " + ob.a + " " + ob.b); After call: 28 10
}
}

class Test { Note: When passing an object reference, a copy of


int a, b; the reference is passed, not a copy of the object itself.
// Method to modify the object 'o'
void set(Test o) {
o.a *= 2; // Modify 'a' of object 'o'
o.b /= 2; // Modify 'b' of object 'o'

System.out.println("Within the method: " + o.a + " " + o.b);


}
}
Returning Objects
In Java, methods can return objects just like they can return public class ReturnObjectExample
primitive data types. {
public static void main(String[] args) {
This allows methods to encapsulate complex behaviors and // Calling a method that returns an object
computations and provide meaningful results in the form of Rectangle rect = createRectangle(5, 10);
objects
class Rectangle { // Using the returned object
int length; int area = rect.calculateArea();
System.out.println("Area of the rectangle: " + area);
int width; }

// Constructor // Method that returns an object of type Rectangle


public static Rectangle createRectangle(int length, int width) {
public Rectangle(int length, int width) {
Rectangle rect = new Rectangle(length, width);
this.length = length; return rect;
this.width = width; }
} }
// Method to calculate area
public int calculateArea() { I:\javaprogram 2024>javac ReturnObjectExample.java
return length * width;
} I:\javaprogram 2024>java ReturnObjectExample
Area of the rectangle: 50
}
Recursion
✓ Java supports recursion.
✓ Recursion is a process in which a method call itself from
within it's body.
✓ The method that calls itself is known as recursive method.
✓ In order to solve a problem recursively two conditions must
be satisfied.
1. The problem must be written in recursive form.
2. The problem must include a stopping condition.
// A simple example of recursion.
class Factorial
{
int factorial (int n)
{
if(n == 0)
return 1;
else
return(n * factorial(n-1)); // Calling the same method
}
}

class Recursion
{
public static void main(String args[])
{
int number = 5;
Factorial f = new Factorial();
System.out.println("Factorial of number "+number+" is : "+ f. factorial(5) );
}
} In this program, once the main method calls
the factorial(5), it calls factorial(4) and it goes
Output on until factorial(0) is called which returns 1 to
F:\>javac Recursion.java factorial(1) which further returns it's result to
F:\>java Recursion factorial(2) and so on until factorial(5) is
Factorial of number 5 is : 120 reached which evaluates the final result and
returns to main method.
Access Control Modifiers
✓ In Java, access control modifiers are keywords that define the visibility and accessibility of classes,
methods, and fields (variables)within a program.
✓ There are four access control modifiers in Java
1. public: is an access modifier in Java that allows classes, methods, and variables to be accessible
from anywhere in the program.
2. private: A private method, or variable is only accessible within the same class.
3. protected: A protected method or variable can be accessed by classes and subclasses in the
same package, as well as by subclasses in a different package
4. default or package: A class, method, or variable with no access control modifier specified (i.e.,
no public, private, or protected keyword) is only accessible within the same package.

✓ A Top level class can use just two of the four access control levels (default or public), members can use all four
✓ Nested Classes and Class Members: Can use private, default, protected, and public.
Access Control Modifiers
1.Public Access Modifier
✓ A member is declared public using public keyword.
✓ This modifier doesn't put any restriction, it can be accessed anywhere.
✓ A public member is accessible everywhere, no matter whether it's in same package or in different package.
✓ Any member can be declared with public modifier whether it's a variable, method, constructor, class, interface or
anything else.
2.Private Access Modifier
✓ A member is declared private using private keyword.
✓ This is the most restrictive access modifier in java.
✓ A private member is accessible within it's own class only.
✓ Variables, methods and constructors can be declared as private.
✓ Top level classes and interfaces can not be declared as private.
3.Protected Access Modifier
✓ A member is declared protected using protected keyword.
✓ A protected member can be accessed within it's own package as well as by a subclass in another package.
✓ This access modifier can be used with variable, method and constructors.
✓ Top level classes and interfaces can not be declared as protected.
4.Default Access Modifier
✓ When a member is declared without any access modifier, it is called default modifier.
✓ A default member is accessible within the package only, that is why it is also known as package modifier.
✓ Any member can be declared with no modifier whether it's a variable, method, constructor, class, interface or
anything else.
Table of access modifier scope

Subclass in
Access Within
Within Class different Everywhere
Modifier package
package

private Yes No No No

default Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes


//Example for access control
class AccessTest {
class Test {
int a; // default access public static void main(String args[]) {
public int b; // public access
private int c; // private access Test ob = new Test();
/*protected applies only
// These are OK, a and b may be accessed directly
when inheritance is involved*/ ob.a = 10;
ob.b = 20;
// methods to access c
// This is not OK and will cause an error
//ob.c = 100; // Error!
void setc(int i){
c = i; // set c's value // You must access c through its methods
ob.setc(100); // OK
}
int getc() { System.out.println(ob.a + " " +ob.b + " " + ob.getc());
}
return c; // get c's value }
}
}
Understanding Static( Static Members or class members)
Instance Variables and Methods
✓ Variables and methods defined inside the class are called instance variables and instance methods.
✓ Each time the class is instantiated (i.e., an object is created), a new copy of these variables and
methods is created.
✓ They are accessed using objects with the dot operator.
Static Members
Variables and methods that are common to all objects of the class and can be accessed without a
specific object.
✓ Variables and methods of classes that don't belong to any specific instance are called static
members and are declared with the static keyword
static int count;
static int passmark = 30;
static int max (int x, int y);
✓ Static members can be accessed before any objects of the class are created and without referring to
any object.
✓ The main() method is static because it must be called before any objects exist.
✓ A Static member can be accessed either by a class or by an object
Static Variables
✓ Static variables (also known as class variables) are shared among all instances of a class.
✓ They are declared using the static keyword.
✓ Used for creating variables that are common to all objects of the same class.
✓ Only one copy of a static variable exists, regardless of how many instances of the class are created.
✓ All instances of the class share the same static variable.
✓ Static variables are initialized once when the class is loaded and remain in memory until the program
terminates
✓ Static variables have default values like instance variables (e.g., 0 for integers, null for object
references etc).
✓ Fields that have the static modifier in their declaration are called static fields or class variables.
✓ Visibility and default values are same as instance variables.
Declaration
Static data type var1,var2.. varn;
Reference
Classname. staticvariable name; Or
Objectname.staticvariable name;
Static Methods
In Java, static methods are methods that belong to the class rather than any particular instance of the class.
They can be called without creating an object of the class.
Static methods can access and modify static variables and call other static methods directly.
They cannot directly access instance variables or instance methods of the class.
Example:
Utility methods(methods in the java.util package) are declared as static method, so that program can call
them directly by using class name and not to wait for object to be ready.
For static methods the memory is allocated only once at the time of class loading.
A common use for static methods is to access static fields
Static methods are also called class methods Reference
Declaration Classname.
Static returntype methodname(parameters) Staticmethodname(arguments);
Or
{ Objectname.
.. Staticmethodname(arguments)
}
Some Properties of static methods
1. It is a method which belongs to the class and not to the object(instance)
2. A static method can access only static data. It can not access non-static data
(instance variables)
3. A static method can call only other static methods and can not call a non-
static method from it.
4. A static method can be accessed directly by the class name and doesn’t need
any object
5. A static method cannot refer to “this” or “super” keywords in anyway
Example:
class Test {
static int a;
static int b;

static void set() {


a = 20;
b = 34;
}
static void print() { I:\javaprogram 2024>javac Test1.java
set();
System.out.println(a + " " + b); I:\javaprogram 2024>java Test1
} 20 34
} 20 34

public class Test1 {


public static void main(String[] args) {
Test.print(); // Using class name to call static method
// Alternatively, creating an instance of Test and calling the method
Test ob = new Test();
ob.print();
}
}
// Demonstrate static variables, and blocks.
Static Block: class Example {
static int x;
• In Java, a static block is a special code block static int y;
marked with the static keyword. // Static block
static {
x= 25;
• It executes only once, when the class is first y = 30;
loaded into memory by the Java ClassLoader. System.out.println("Static block initialized.");
• A static block is executed when the class is first }
loaded. }
class StaticEx
• A typical use of static blocks is to initialize static {
public static void main(String[] args)
variables in a class. {
System.out.println("Inside main method.");
• This ensures these variables are initialized System.out.println("Static variable: " +Example. x);
correctly before any objects are instantiated or any System.out.println("Another static variable: " +Example. y);
other class operations are performed. }
}
• If a class has different static variables that need to
be initialized individually, then you should use a I:\javaprogram 2024>javac StaticEx.java
static block. I:\javaprogram 2024>java StaticEx
syntax for a static block Inside main method.
Static block initialized.
static { // Code here } Static variable: 25
Another static variable: 30
Introducing Nested and Inner Classes
Nested Class
✓ A class declared within another class is called nested class.
✓ The scope of a nested class is bounded by the scope of it’s enclosing class.
Syntax
class EnclosingClass {
...
class NestedClass {
...
}
}
Example:
If a class Address is declared within the class Employee , then the Address class is known to the Employee class only and not outside the
Employee class.

class Employee // Enclosing Class


{
class Address // Nested class
{
}
}
✓ A nested class can access members of the enclosing class including its private members , whereas the enclosing class does not have
access to members of the nested class
✓ (ie) the enclosing class does not have access to the members of the nested class.
Nested Class
Outerclass

This class cannot access members in the nested class.

A nested class

This class has access to all the members of its outrer class

No class other than the outer class “knows” of the existence of this class

Its scope extends only to the enclosing class


Types of nested classes
There are two main types of nested classes: static nested classes and non-
static nested classes (inner classes):
1.Static Nested Classes: These are declared inside the outer class with the
static keyword. They can't directly access instance variables of the outer
class. Instances of static nested classes can be created without needing an
instance of the outer class.

2. Non-Static Nested Classes (Inner Classes): These are declared without


the static keyword inside the outer class. They can access instance variables
and methods of the outer class. To create an instance of an inner class, an
instance of the outer class must first be created.
static nested class
✓ A static class created inside an outer class is known as a class Outer
{
static nested class.
static int data=30;
✓ Static nested classes are declared as static within the outer static class Inner // static class
class. {
✓ They can be accessed using the outer class name followed static void msg()
by the dot operator. {System.out.println("data is "+data);
}
✓ Static nested classes can contain both static and non-static }
members, similar to regular top-level classes. }
✓ They cannot access non-static members of the outer class. class staticnested
{
✓ However, they can access static data members of the outer
public static void main(String args[])
class, including private ones. {
✓ Static nested classes cannot access non-static (instance)
data members or methods. Outer.Inner.msg();
}
}
Output: data is 30
Non- static or Inner classes
✓ Non-static nested classes are also known as inner classes
✓ It has access to members (variables and methods )of the enclosing class (outer class).
✓ Since the inner class exists within the outer class, you must instantiate the outer class first, in
order to instantiate the inner class.
✓ (ie) To access the inner class, create an object of the outer class, and then create an
object of the inner class:

There are two types of inner classes.


1. Member inner class
2. Local inner class
1.Member inner class
✓ A class that is declared inside a class but outside a method is known as member inner class.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
Output :
} display: outer_x = 100
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
2.Local inner class
✓ A class that is created inside a method is known as local inner class. If you want to invoke the methods of local
inner class, you must instantiate this class inside the method.
class Outer {
int outer_x = 100;
void test() {
class Inner { // inner class defined inside a method
void display() {
System.out.println("display: outer_x = “ + outer_x);
}
}
Inner inner = new Inner();
inner.display();
F:\>javac InnerClassDemo.java
}
}
F:\>java InnerClassDemo
class InnerClassDemo {
display: outer_x = 100
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Inheritance
Inheritance Basics
✓ Inheritance is a fundamental feature of Object-Oriented Programming.
✓ It involves creating a new class based on an existing class.
✓ The existing class is known as the superclass, and the new class is referred to as the subclass.
✓ A subclass inherits all instance variables and methods defined by its superclass and can also add its own unique
elements.
✓ When a class extends another class, it inherits all non-private members, including fields and methods.
✓ In Java, inheritance is best understood through the relationship between a superclass (parent) and a subclass
(child).
✓ It establishes an "is-a" relationship between the superclass and its subclass.
✓ The extends keyword is used in Java to indicate inheritance.

85
Advantages of Inheritance
1. Code Reusability: Inheritance allows subclasses to inherit methods and behaviors from their superclass,
avoiding code duplication and promoting reuse across multiple subclasses.
2. Extensibility: Subclasses can add new methods from the superclass, enhancing functionality without
altering the original code.
3. Maintenance: Changes made to the superclass automatically apply to all subclasses, reducing redundancy
and ensuring consistent behavior across related classes.
4. Overriding (Run time Polymorphism): Subclasses can have methods with the same name and parameters
as those in their superclass. These methods in the subclass provide specific functionalities that may differ
from those in the superclass.
5. Data Hiding: Base class can hide some of its data and code by making them private.
Types of inheritance

1. Single inheritance(one super class): A subclass inherits from only one


superclass.
2.Multiple inheritance(several super class): A subclass inherits from multiple
super classes directly..
3. Hierarchical inheritance(one super class, many subclass) : Multiple
subclasses inherit from a single superclass.
4. Multilevel inheritance(derived from derived class) : The mechanism of
deriving a class from another ‘derived class’ is known as multilevel
inheritance.
Types of Inheritance
// example of single inheritance
Single Inheritance class A
{
The general form is int i=10;
class subclass-name extends sperclas-sname void showi()
{
{ System.out.println (" i :=" + i );
Variable declaration }
}
Methods declaration class B extends A
} { int j = 20;
int k = i+ j;
✓ The extends keyword in Java signifies void showk()
that the properties of the superclass are {
System.out.println ( "K:=" + k);
inherited by the subclass. }
}
✓ Subclasses do not inherit private class singleinherit
members from their superclass. { public static void main (String args[])
{
✓ Each class in Java can have at most one B ob = new B();
superclass. ob.showi();
ob.showk();
Example: Single Inheritance }
}
output
H:\>javac singleinherit.java
H:\>java singleinherit
i :=10
K:=30
Member access rules
A subclass includes all of the members (default, public, protected) of its
superclass except private members.
class A { class AccessDemo {
private int v = 10; public static void main(String[] args) {
int d = 20; B b = new B();
public int b = 30; b.disp();
protected int p = 40; }
} }
class B extends A { }
void disp() {
// Private member 'v' cannot be accessed directly in subclass I:\javaprogram 2024>javac AccessDemo.java
// System.out.println("v value : " + v); // Error: v is private in class A I:\javaprogram 2024>java AccessDemo
System.out.println("d value : " + d); // Accessing default member 'd' d value : 20
System.out.println("b value : " + b); // Accessing public member 'b' b value : 30
System.out.println("p value : " + p); // Accessing protected member 'p' p value : 40
}
}
Multilevel Inheritance
✓ When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance.
✓ Multilevel inheritance can go up to any number of level.

class three extends two //Sub class of two


/* Multilevel Inheritance example */ {
class one //Super class void mul()
{ {
int x=10,y=20; System.out.println("This is the method in
void display() class three");
{ System.out.println("X*Y= "+(x*y));
System.out.println("This is the method in class one"); }
System.out.println("Value of X= "+x); }
System.out.println("Value of Y= "+y); /* Main class */
} class Multilevel
} {
class two extends one //Sub class public static void main(String args[])
{ {
void add() three t=new three(); //Object of class three
{ t.display(); //Calling method of class one
System.out.println("This is the method in class two"); t.add(); //Calling method of class two
System.out.println("X+Y= "+(x+y)); t.mul(); //Calling method of class three
} }
} }

Hierarchical Inheritance
When two or more classes inherits a single class, it is
known as hierarchical inheritance.
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening"); F:\>javac HierachicalInheritance.java
}
} F:\>java HierachicalInheritance
class Principal extends Teacher { Evaluating
void evaluate() { Teaching subject
System.out.println("Evaluating");
}
}
class HierachicalInheritance {
public static void main(String argu[]) {
Principal p = new Principal();
p.evaluate();
p.teach();
// p.listen(); will produce an error, Principal class extends
only Teacher class , not Student class
The ‘is- a’ Relationship
Inheritance is a mechanism for expressing “Is-A” relationships in Java.
Inheritance defines is-a relationship between a Super class and its Sub class.
(ie) the child is a more specific version of the parent
Class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class
}
Now based on above example. In OOPs term we can say that,
Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Note:
✓ When there is an extends or implement keyword in the class declaration in Java, then the specific class
is said to be following the Is-A relationship.
✓ Inheritance is uni-directional. For example, House is a building. But not all buildings are houses.
Using Super Keyword
✓ In Java, the super keyword is used to access the member of the superclass from the
subclass.
Uses of super keyword
1. super can be used to refer immediate super class instance variable.
2. super can be used to invoke immediate super class method.
3. super() can be used to invoke immediate super class constructor.
1.super can be used to refer immediate super class instance variable
class Superclass
Overriding Instance Variables of superclass {
int num = 100;
✓ When a variable in a subclass has the }
same name as a variable in its superclass, class Subclass extends Superclass
the subclass variable overrides or hides {
int num = 110;
the superclass variable. void printNumber(){
✓ This behavior is referred to as variable System.out.println("Value num in the sub class "+num);
hiding or variable overriding in Java. System.out.println("Value num in the super class "+super.num);
}
✓ To access the value of the hidden }
superclass variable, the super keyword is class variableoverride
{
used."
public static void main(String args[])
the general form is : super.variable; {
Subclass obj= new Subclass();
obj.printNumber();
}
}

F:\>javac variableoverride.java
F:\>java variableoverride
Value num in the sub class 110
Value num in the super class 100
2. super can be used to invoke immediate super class method
Method Overriding
✓ Method overriding in Java refers to the process of writing a method in a subclass with
the same signature (name, parameters, and return type) as a method in its superclass.
✓ When an overridden method is called from within a subclass, it always refers to the
version of that method defined by the subclass.
✓ This means the version of the method defined by the superclass is hidden or
overridden.
✓ If you need to access the superclass version of an overridden method, you can use the
super keyword.
✓ This allows you to explicitly invoke the superclass's method implementation.
✓ Method overriding occurs only when the names and the type signatures (parameters
and return type) of the methods are identical in both the superclass and subclass.
✓ If these criteria are not met, the methods are considered overloaded, not overridden.
✓ In overriding parent class method is called overridden method and Child class method
is called overriding method
Note: We cannot override the method declared as final and static.
// Parent class
Example – Method overriding
class Parentclass {
// Method in the parent class
void display() {
System.out.println("Parent class method");
}
}
// Subclass extending Parentclass
class Subclass extends Parentclass {
// Overriding method from Parentclass
void display() {
System.out.println("Child class method");
}
// Method to demonstrate method calls
void printMsg() {
display(); // Calls the overridden display() method in Subclass
super.display(); // Calls the display() method in Parentclass using
super
}
}
// Main class F:\>javac Methoverride.java
class Methoverride {
public static void main(String args[]) {
Subclass obj = new Subclass(); F:\>java Methoverride
obj.printMsg(); // Calls printMsg() in Subclass Child class method
} Parent class method
}
3.super() can be used to invoke immediate super class constructor.

✓ Subclass constructor is used to initialize the instance variables of the subclass as well
as in the super class
✓ Super is a keyword used to call the super class constructor from sub class
constructor.
The general form is super(argument list);
Rules to be followed
i) super keyword is used only within a subclass constructor.
ii) Super() must be the first statement executed inside a subclass constructor
iii) The arguments in the super() must match the arguments in the constructor defined
in the superclass.
//Using super to call superclass constructors class SBAccount extends Account {
class Account { double rate;
int accountNumber, balance; // Constructor to initialize accountNumber, balance, and rate
// Calls the superclass constructor to initialize accountNumber and balance
SBAccount(int accountNumber, int balance, double rate) {
// Constructor to initialize accountNumber
super(accountNumber, balance); // Call the superclass constructor
and balance
this.rate = rate;
Account(int accountNumber, int balance) { }
this.accountNumber = accountNumber; // Method to display the interest rate
this.balance = balance; void displayInterestRate() {
} System.out.println("Interest Rate = " + rate);
}
// Method to credit amount to the balance }
void credit(int amount) { class AccountDemo {
balance = balance + amount; public static void main(String[] args) {
} // Create an SBAccount object with accountNumber 1001, balance 5000, and
interest rate 6.5
// Method to debit amount from the balance SBAccount obj1 = new SBAccount(1001, 5000, 6.5);
void debit(int amount) { obj1.credit(2000);
balance = balance - amount; obj1.debit(1000);
obj1.displayBalance();
}
// Display the interest rate
obj1.displayInterestRate();
// Method to display the current balance }
void displayBalance() { }
System.out.println("Balance = " + balance); OUTPUT:
}
} Balance =6000
Interest Rate =6.5
Differences between method overloading and method overriding.

Method Overloading Method Overriding


Defining multiple methods with the Defining multiple methods with the same
same name but with different signatures name and same signatures is called
is called method overloading. method overriding.
Method overloading is done in the same Method overriding is done in super and
class. sub classes.
In method overloading, method return In method overriding method return type
type can be same or different. should also be same.
The JVM determines which method to The JVM chooses the method based on
call based on the method signatures. the object's data type.
Method overloading is done when the Method overriding is done when the
programmer wants to extend the already programmer wants to provide a different
available features. implementation(body) for the same
feature.
Dynamic Method Dispatch or Runtime Polymorphism

✓ Dynamic method dispatch or run time polymorphism is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
✓ Dynamic method dispatch is important because this is how Java implements run-time
polymorphism.
✓ Runtime polymorphism is the ability of a single method call to behave differently based on the
actual object type that invokes the method.
✓ In java, a superclass reference can refer to objects of its class or any of its subclasses(also
known as upcasting).
✓ Java uses this fact to resolve calls to overridden methods at run time.
✓ That is, an overridden method is called through the reference variable of a super class.
✓ When an overridden method is called using a superclass reference, the actual method that
gets executed is determined at runtime based on the object being referred to, not the
reference variable's type.
✓ This means that the Java Virtual Machine (JVM) looks at the actual object type and calls the
corresponding method of that object's class.
Example: class Dyanamic {
class Bank { public static void main(String[] args) {
double getInterestRate() { Bank bank; // Reference variable of a super class Bank
return 0.0; // Assigning the reference variable to a SavingsAccount object
} bank = new SavingsAccount();
} // Calls the getInterestRate method of SavingsAccount
System.out.println("Savings Account Interest Rate: " + bank.getInterestRate() + "%");
class SavingsAccount extends Bank {
//Overriding // Assigning the reference variable to a FixedDeposit object
double getInterestRate() {
bank = new FixedDeposit();
return 4.0;
// Calls the getInterestRate method of FixedDeposit
}
System.out.println("Fixed Deposit Interest Rate: " + bank.getInterestRate() + "%");
}

class FixedDeposit extends Bank { // Assigning the reference variable to a RecurringDeposit object
//Overriding bank = new RecurringDeposit();
double getInterestRate() { // Calls the getInterestRate method of RecurringDeposit
return 6.5; System.out.println("Recurring Deposit Interest Rate: " + bank.getInterestRate() + "%");
} }
} }
class RecurringDeposit extends Bank {
//Overriding I:\javaprogram 2024>java Dyanamic
double getInterestRate() { Savings Account Interest Rate: 4.0%
return 5.0; Fixed Deposit Interest Rate: 6.5%
} Recurring Deposit Interest Rate: 5.0%
}
class Triangle extends Figure {
// Using run-time polymorphism. Triangle(double a, double b) {
class Figure {
super(a, b);
double dim1;
double dim2; }
Figure(double a, double b) { // override area for right triangle
dim1 = a; double area() {
dim2 = b; System.out.println("Inside Area for Triangle.");
} return dim1 * dim2 / 2;
double area() { }
System.out.println("Area for Figure is
undefined."); }
return 0;
} class FindAreas {
} public static void main(String args[]) {
class Rectangle extends Figure { Figure f = new Figure(10, 10);
Rectangle(double a, double b) { Rectangle r = new Rectangle(9, 5);
super(a,b);
}
Triangle t = new Triangle(10, 8);
// override area for rectangle Figure figref;
double area() { figref = r;
System.out.println("Inside Area for System.out.println("Area is " + figref.area());
Rectangle."); figref = t;
return dim1 * dim2;
System.out.println("Area is " + figref.area());
}
} figref = f;
System.out.println("Area is " + figref.area());
Inside Area for Rectangle. }
Area is 45 }
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
Abstract Methods &Abstract Classes
✓ Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
✓ In Java, abstraction is achieved through abstract classes or interfaces
✓ In Java, a superclass can define a general form shared by all subclasses, with each subclass
providing its specific implementation.
✓ In Java, an abstract class defines methods that subclasses must implement.
Abstract methods
In Java, an abstract method is a method that is declared but not implemented in an abstract
class.
Abstract methods are used to define the structure or contract that subclasses must follow.
Syntax:
abstract type name (parameter-list);

✓Abstract methods do not have a body


Examples:
1.abstract double area();
2. abstract int sumOfThree(int n1, int n2, int n3);
Abstract Classes
✓An abstract class in Java is a class that contains at least one abstract method.
✓Additionally, it can also contain concrete methods (methods with a body) and instance
variables.
✓The presence of at least one abstract method is what distinguishes an abstract class from
a regular class in Java.
Syntax:
abstract class MyClass{
......
}
✓ Instances of an abstract class cannot be created directly, but references to abstract classes can be
created.
✓ An abstract class can have instance variables, static members, and constructors, like regular
classes.
✓ Must be extended by a subclass: To use an abstract class, a subclass must be created that inherits
from it and provides implementations for any abstract methods.
✓ Any subclass that extends an abstract class must either implement all the abstract methods of
the superclass or be declared abstract itself.
✓ A class can be declared abstract even if it does not contain any abstract methods, preventing it
from being instantiated.
// Abstract class Shape with an abstract method area() // Main class to test the Shape classes
abstract class Shape { class TestShape3 {
abstract public double area(); public static void main(String[] args) {
} // Creating an instance of Square
// Subclass Square extends Shape and provides implementation for the area method
Square s = new Square(12.0);
class Square extends Shape {
double length;
// Printing the area of the square
// Constructor to initialize length System.out.println("The area of square s is " + s.area());
public Square(double length) {
this.length = length; // Creating an instance of Circle (note the capital 'C')
} Circle c = new Circle(5.0);
// Implementation of the area method for Square
// Printing the area of the circle
public double area() {
return length * length;
System.out.println("The area of circle c is " + c.area());
} }
} }
Output:
// Subclass Circle extends Shape and provides implementation for the area method The area of square s is 144.0
class Circle extends Shape {
The area of circle c is 78.53981633974483
double radius;
// Constructor to initialize radius
public Circle(double radius) {
this.radius = radius;
}

// Implementation of the area method for Circle


public double area() {
return Math.PI * radius * radius;
}
Example2:
abstract class Employee{
abstract int getSalary(); // abstract method
}
class Developer extends Employee{
int salary;
public Developer(int s){
salary = s;
}
int getSalary(){ return salary;
}
}
F:\>javac abstract1.java
class Driver extends Employee{
int salary; F:\>java abstract1
public Driver(int t){ Salary of developer : 5000
salary = t; Salary of driver : 3000
}
int getSalary(){ return salary;
}
}
class abstract1
{
public static void main(String[] args)
{
Developer d1 = new Developer(5000);
Driver d2 = new Driver(3000);
System.out.println("Salary of developer : " + d1.getSalary());
System.out.println("Salary of driver : " + d2.getSalary());
}
}
Using final with Inheritance
The keyword final has three uses:
1. To create a named constant
2. To prevent overriding
3. To prevent inheritance
1.To create a named constant :
✓ A variable can be declared as final. Doing so prevents its contents from being modified.
✓ This means that you must initialize a final variable when it is declared.
✓ A final variable cannot be reassigned once initialized.
Example: final float pi=3.14;

class FinalDemo{
public static void main(String args[]){
final int i=20;
System em.out.println(i);
//i=i+1; can’t assign a value to final variable i
//System.out.println(i); cannot assign a value to final variable i
}
}
To prevent overriding
✓ A method declared with the final keyword cannot be overridden by subclasses.
✓ This is useful when you want to ensure that the implementation of a method remains unchanged in any subclass.
✓ (ie) A final method cannot be overridden by subclasses.

class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}

class Final1 extends FinalDemo {


// try to override final method, not allowed
public final void display() {
System.out.println("The final method is overridden.");
}
}
class Finalmeth
{
F:\>javac Finalmeth.java
public static void main(String[] args) { Finalmeth.java:10: error: display() in
Final1 obj = new Final1(); Final1 cannot override display() in Final
obj.display(); Demo
} public final void display() {
} ^
overridden method is final
1 error
To prevent inheritance
✓ A class declared with the final keyword cannot be subclassed.
✓ This means that no other class can extend it.
✓ This is useful when you want to prevent inheritance for security reasons or to maintain the design of your application.
(ie) A final class cannot be subclassed.

final class Finalclasdemo{ // create a final class


public void display() {
System.out.println("This is a final method.");
}
}
class Final1 extends Finalclasdemo { // try to inherit final class , not allowed
public void display() {
System.out.println("The final method is overridden.");
}
}
class Finalclass
{
F:\>javac Finalclass.java
public static void main(String[] args) {
Finalclass.java:8: error: cannot inherit
Final1 obj = new Final1();
obj.display();
from final Finalclasdemo
}}
class Final1 extends Finalclasdemo {
^
1 error
The Object Class
✓ In Java, the Object class is the root of the class hierarchy.
✓ Every class(pre-defined or user defined) in Java is a subclass of Object, either directly or indirectly.
✓ This means that Object is the ultimate superclass of all classes and provides fundamental methods that are
available to every Java object.
✓ This means that a reference variable of type Object can refer to an object of any other class.
✓ Object defines the following methods, which means that they are available in every object.
Example:
// Class definition for MyClass
class MyClass {
int x = 10; // An instance variable initialized to 10
Output:
// Overriding the toString() method from the Object class MyClass [x=10]
public String toString() { class MyClass
// Return a string representation of the MyClass object
return "MyClass [x=" + x + "]";
}
}

// Main class to demonstrate the use of Object class methods


public class ObjectClassExample {
public static void main(String[] args) {
MyClass obj = new MyClass(); // Creating an instance of MyClass

// Implicit use of Object's toString() method


// This will automatically call the overridden toString() method of MyClass
System.out.println(obj); // Output: MyClass [x=10]

// Explicit use of Object's getClass() method


// This will return the runtime class of the object
System.out.println(obj.getClass()); // Output: class MyClass
}
}

You might also like