0% found this document useful (0 votes)
27 views69 pages

Java Object-Oriented Programming Basics

Uploaded by

helpboost1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views69 pages

Java Object-Oriented Programming Basics

Uploaded by

helpboost1001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Object Oriented

Programming with JAVA

Course Code: BCS306A

MODULE-2

CHAPTER-1

INTRODUCING CLASSES
Chapter Contents:
• Introducing Classes
Class Fundamentals, Declaring Objects, Assigning Object
Reference Variables, Introducing Methods, Constructors,
The this Keyword, Garbage Collection.
• Textbook: Chapter 6
Objects and Classes in Java
 An object in Java is the physical as well as a logical
entity, whereas, a class in Java is a logical entity
only.
 An entity that has state and behavior is known as an
object e.g., chair, bike, pen, table, car, etc.
 It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking
system.
an object consists of :
 State : It is represented by attributes of an object. It
also reflects the properties of an object.
 Behavior : It is represented by methods of an object.
It also reflects the response of an object with other
objects.
 Identity : An object identity is typically implemented
via a unique ID.
•The value of the ID is not visible to the external user.
However, it is used internally by the JVM to identify
each object uniquely.
Contd..

• An object is an instance of a class. A class is a template or


blueprint from which objects are created. So, an object is
the instance (result) of a class.
• Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
Class Fundamentals
 A class is a group of objects which have common properties.
 It is a template or blueprint from which objects are created.
 It is a logical entity. It can't be physical.
 Class is a collection of the data items and functions. The data items
are called as fields and function are called as methods.
 Java is said to be true object oriented programming language
because without class we cannot do anything.
 A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
The General Form of a Class
Example:
 A class is declared by use of the class class Student { // Defining a class
keyword. String name; // Fields (variables)
 A simplified general form of a class definition int age;
is: void display() { // Method
Syntax: [Link]("Name: " + name);

class ClassName { [Link]("Age: " + age);

// Instance variables (fields) }

type variable1; }

public class Main { // Main class


type variable2;
public static void main(String[] args) {
... Student s1 = new Student(); // Creating an object of Student
// Methods [Link] = "Ravi"; // Assigning values
returnType methodName1(parameters) { [Link] = 20;

// method body [Link](); // Calling method

} }

}
returnType methodName2(parameters) {
// method body
}
}
Contd..
 The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
 Collectively, the methods and variables defined within a class are called
members of the class.
 Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy of
these variables.
A Simple Class (Box Class)
 Define a class called Box that defines three instance variables:
width, height, and depth.
Currently, Box does not contain any methods.
class Box {
double width;
double height;
double depth;
}
This class defines a new data type called Box. Use this name to declare objects of
type Box.
OBJECT CREATION

 To create a Box object, use a statement like the following:


 Box mybox = new Box(); // create a Box object called mybox
After this statement executes, mybox will refer to an instance of Box.
Thus, it will have "physical" reality.
Every Box object will contain its own copies of the instance variables
width, height, and depth.

DATA MEMBER ACCESS:


 To access these variables, use the dot (.) operator.
 The dot operator links the name of the object with the name of an instance variable.

Example:
•Assign the width variable of mybox the value 100.
[Link] = 100;

•This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100.
•In general, you use the dot operator to access both the instance variables and the methods within an object.
DECLARING AN OBJECT
Obtaining objects of a class is a two-step process.
[Link] a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
[Link] an actual, physical copy of the object and assign it to
that variable. You can do this using the new operator.

•The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it. This reference is, essentially, the address in memory
of the object allocated by new.

•This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
Example:
Step-1: Box mybox; // declare reference to object

Step-2: mybox = new Box(); // allocate a Box object

mybox = new Box();


Above statement combines the two steps.
General form:
Class_var = new classname();

 Here, class-var is a variable of the class type being created. The classname is the name
of the class that is being instantiated.
 The class name followed by parentheses specifies the constructor for the class.
 A constructor defines what occurs when an object of a class is created (especially
initialization of instance variables).
 The new operator dynamically allocates memory for an object.
The advantage is that:
The program can create as many or as few objects as it needs during the execution of
your
program (Memory is finite and new may not be able to allocate memory because
insufficient memory exists).
Object Reference Variables
Consider the statements:
Box b1 = new Box();
Box b2 = b1;
The assignment of b1 to b2 did not allocate any
memory or copy any part of the original object. Although b1 and b2 both refer to the
It simply makes b2 refer to the same object as same object, they are not linked in any
does b1. other way.
•After this fragment executes, b1 and b2 will both A subsequent assignment to b1 will simply
refer to the same object. unhook b1 from the original object without
•Thus, any changes made to the object through affecting the object or affecting b2.
b2 will affect the object to which b1 is referring,
since they are the same object.
Consider the statements:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;

•Box b1 = new Box();


Creates a new Box object and assigns its reference to b1.
•Box b2 = b1;
Copies the reference from b1 to b2. Now both b1 and b2 refer to the same object.
•b1 = null;
Unhooks b1 from the object. But b2 still refers to the original object, so it is not affected.

This demonstrates that object references in Java are independent — changing one reference
doesn't affect others pointing to the same object unless you modify the object itself.
INTRODUCING METHODS

The general form of a method:


type name(parameter-list) {
// body of method
}
 Here, type specifies the type of data returned by the method. If the method does not return a value, its return
type must be void.
 The name of the method is specified by name. This can be any legal identifier other than those already used
within the current scope.
 The parameter list is a sequence of type and identifier pairs separated by commas. If the method has no
parameters, then the parameter list will be empty.
Introducing methods contd..
Methods that have a return type other than void, return a value
to the calling routine using the return statement: class BoxDemo3 {

return value; public static void main(String[] args) {


Here, value is the value returned (via variable or literal). Box mybox1 = new Box();
Example: [Link] = 10;
[Link] = 20;
Box class and Volume() method returning void.
[Link] = 15;
class Box {

double width;

double height; // display volume of first box


double depth; [Link]();
void volume() { // display volume of a box }
[Link]("Volume is "); }
[Link](width * height * depth);

}
Main Method
}

•The statement [Link](); invokes the volume() method on mybox1. That is, it calls volume()
relative to the mybox1 object, using the object’s name followed by the dot operator.

•Thus, the call to [Link]() displays the volume of the box defined by mybox1.
Introducing methods contd..
Returning a Value
•A better way to implement volume() is to compute the volume of the box and return the result to the caller.
•This makes the volume available to other parts of the program.
Example:
class Calculator {
// Method with return type Output:
Square of 5 is: 25
int square(int number) {
return number * number;
}
}
public class SquareDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
int input = 5;
int result = [Link](input);
[Link]("Square of " + input + " is: " + result);
}
}
Methods with parameters
•Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety of
data and/or be used in a number of slightly different situations.
•It is important to keep the two terms: parameter and argument straight.
A parameter is a variable defined by a method that receives a value when the method is called.
•An argument is a value that is passed to a method when it is invoked.

Example:

int x, y; Argum
ent
x = square(5);

int square(int i) { Pa
return i * i; ra me
} ter
Methods with parameters
Example:
public class Greeting {
void sayHello(String name) { // Method that takes a parameter and prints a
greeting message
[Link]("Hello, " + name + "!");
}
public static void main(String[] args) {
Greeting greet = new Greeting(); // Create an object of Greeting class

[Link](“Ram"); // Call method with argument “Ram"


[Link](“Raju"); // Call method with argument “Raju"
}
}

output
Hello, Ram!
Hello, Raj!
.

Constructors

 A constructor in Java is a special method that is called automatically when an


object is created.
Its main purpose is to initialize the object (i.e., set its initial values).
 It has the same name as the class in which it resides and is syntactically similar to a
method.
 Once defined, the constructor is automatically called when the object is created,
before the new operator completes.
 Constructors have no return type , not even void because the implicit return type of a
constructor is the class type itself
 It is the constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor (manual in Java)

1. Default Constructor
A constructor without any parameters.
If you don’t write any constructor, Java automatically provides a default one.
public class Student {
String name;
int age;
Student() { // Default Constructor
name = "Unknown";
age = 0; output
}
void display() { Unknown - 0
[Link](name + " - " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
[Link]();
}
}
Types of Constructor

[Link] Constructor void display() {


 A constructor that accepts arguments to
[Link](name + " - " +
initialize object data directly.
age);
Example:
public class Student { }
String name; public static void main(String[] args) {
int age; Student s2 = new Student("Arun",
// Parameterized Constructor 20); // Parameterized constructor
Student(String n, int a) { [Link]();
name = n;
}
age = a;
} }
 Output
Arun - 21
Types of Constructor
 3. Copy Constructor Student(Student s) {//Copy Constructor

•Java doesn't have built-in copy constructors — we name = [Link];


define them manually. age = [Link];

•Used to create a new object with the same values as }


another. void display() {
Example
[Link](name + " - " + age);
public class Student {
}
String name;
public static void main(String[] args) {
int age;
Student s1 = new Student("Bob", 22);
// Parameterized Constructor
Student s2 = new Student(s1);
Student(String n, int a) {
[Link]();
name = n;
age = a; }

} }

Output
Bob - 22
The This Keyword

•this is a reference variable in Java that refers to the current object of the class.
•It is commonly used to resolve naming conflicts and perform object-based operations within class
methods or constructors.

Why Use this?


[Link] refer to current class variables
[Link] call another constructor (constructor chaining)
[Link] pass current object as an argument
[Link] return current object from a method
This Keyword
Example 1 – Resolving Naming Conflict

public class Student {

String name; Output


int age;
Alice - 20
Student(String name, int age) {

[Link] = name; // Refers to instance variable

[Link] = age;

void display() {

[Link](name + " - " + age);

public static void main(String[] args) {

Student s1 = new Student("Alice", 20);

[Link]();

}
This keyword

Example 2 – Constructor Chaining with this()


public class Student {
String name;
int age; Output

Student() { Unknown -0
this("Unknown", 0); // Calls parameterized constructor
}

Student(String name, int age) {


[Link] = name;
[Link] = age;
}

void display() {
[Link](name + " - " + age);
}

public static void main(String[] args) {


Student s = new Student();
[Link]();
}
}
This Keyword
Example 3 – Returning Current Object

public class Student { Summary Table


String name;

Student setName(String name) {


[Link] = name;
return this; // returns current object
}

void display() {
[Link]("Name: " + name);
}

public static void main(String[] args) {


Student s = new Student();
[Link]("John").display(); // Method
chaining
}
}

Output

Name: John
Garbage Collection
 Garbage Collection (GC) in Java is the process by which the Java Virtual Machine (JVM)
automatically removes unused (unreferenced) objects from memory.
 This helps to free up memory and avoid memory leaks.
 Java handles memory management automatically, so you don’t need to manually delete objects.
How It Works:
🔸 When no references to an object exist, that object is assumed to be no longer needed, and the
memory it occupies can be reclaimed by the JVM.
🔸 There is no need to explicitly destroy objects. Java handles this automatically.
🔸 Garbage collection occurs sporadically, not immediately after an object becomes unused.
🔸 GC does not occur just because an object becomes unreferenced. It's triggered by the JVM
based on memory needs and system behavior.
Garbage Collection

public class GarbageExample {


public void finalize() {
[Link]("Object is garbage collected");
}
public static void main(String[] args) {
GarbageExample obj1 = new GarbageExample();
GarbageExample obj2 = new GarbageExample();
obj1 = null; // No reference → eligible for GC
obj2 = null;
[Link](); // Request garbage collection
}
}
Output
Object is garbage collected
Object is garbage collected
Garbage Collection

When Is an Object Eligible for GC?


 An object is eligible for garbage collection when no active
part of the program has any reference to it.
Example:

Employee emp = new Employee(); // Object created


emp = null;
Garbage Collection

Finalize() Method

•Defined in Object class


•Called before the object is removed by GC
•Can be overridden to perform cleanup
Example:

protected void finalize() throws Throwable {


// cleanup code
}
Review Questions

1. Write the general form of a class in Java. Explain class definition and member access with suitable program.
2. Explain two step procedure to create objects (class instance) with suitable program.
3. Explain assignment of objects with suitable example.
4. Explain general form of method definition in Java. Explain method definitions with suitable programs for:
a. Methods with no parameters and no return value
b. Methods with no parameters and return value
c. Methods with parameters and return value
5. Explain the role of constructors with an example. Explain with a program
(a) default constructor
(b) parameterized constructor

6. Explain the role of ‘this’ in parameter and instance variable name collision handling with suitable programming example.

7. Develop a Java program to define a class ‘2DBox’ with data members ‘length and width’. Define a class member method to calculate the area
of 2DBox and print box dimensions. Develop main method to illustrate the creation of objects, member access and use of methods suitably.

8. Develop a Java program to define a class ‘Customer’ with data members like Name, Employment and Age. Define a constructor and methods
to change employment and age. Develop main method to illustrate object creation, member access and invocation of methods suitably.
MODULE-2

CHAPTER-2

METHODS AND CLASSES


Chapter Contents:
Methods and Classes:
Overloading Methods, Objects as Parameters, Argument Passing, Returning Objects,
Recursion, Access Control, Understanding static, Introducing final, Introducing Nested and
Inner Classes.
Textbook: Chapter 6,7
What is Method Overloading?
 Definition:
Method Overloading allows a class to have more than one method
with the same name, as long as their parameter lists differ.
 Overloading is compile-time polymorphism.
 "Method Overloading is when we have multiple methods with the
same name in a class but with different parameter lists—either in
number, type, or order. The compiler differentiates between them
during compilation, hence it's called compile-time polymorphism."
Why Use Method Overloading?
 Simplifies code by avoiding multiple method names.
 Supports intuitive and consistent interfaces.
 Facilitates reusability of code for similar operations.

"Imagine you're creating an add() method—sometimes you want to add two integers, other times two doubles, or maybe
three numbers. Instead of naming them addInt, addDouble, or addThreeNumbers, you can just overload add() with
different parameters. This makes the API easier to understand and maintain."
Rules for Method Overloading
 Must have the same method name.
 Parameter list must be different in:
 Number of parameters
 Type of parameters
 Order of parameters
 Return type alone cannot distinguish methods.

"For method overloading to work, the compiler must be able to distinguish the
methods based on the parameter list. The return type isn’t considered when
overloading, so changing only the return type will result in a compilation error."
public class MathOpsDemo {
Example of Overloading public static void main(String[] args) {
MathOps math = new MathOps();
// Calling add method with two integers
// File: [Link]
int result1 = [Link](10, 20);
class MathOps {
[Link]("Sum of 10 and 20 (int): " + result1);
// Method to add two integers
// Calling add method with two doubles
int add(int a, int b) {
double result2 = [Link](5.5, 6.5);
return a + b;
[Link]("Sum of 5.5 and 6.5 (double): " +
}
result2);
// Method to add two double values
// Calling add method with three integers
double add(double a, double b) { int result3 = [Link](1, 2, 3);
return a + b; [Link]("Sum of 1, 2 and 3 (int): " + result3);
} }
// Method to add three integers }
int add(int a, int b, int c) { Expected Output:
return a + b + c; Sum of 10 and 20 (int): 30
} Sum of 5.5 and 6.5 (double): 12.0
} Sum of 1, 2 and 3 (int): 6
How it Works?

 The same method name add is used.


 Java automatically selects the correct method based on:
The number of arguments.
The types of arguments (int vs double).
 This is a classic example of compile-time polymorphism.
What Does “Objects as Parameters” Mean?
 In Java, objects can be passed to methods just like primitive data types.
 The method can access and modify the object's fields and methods .
"When we pass an object to a method, we’re actually passing a
reference to that object. This allows the method to interact with the
original object and not just a copy."

Why Use Objects as Parameters?


 To reuse methods for different instances.
 group related data and behavior.
 To avoid returning multiple values.

Using objects as parameters enables you to design flexible methods


that work with different inputs. This helps maintain clean and modular
code
Example Program for Objects as Parameters
// Rectangle class definition
class Rectangle { // Main class
int length; public class ObjectAsParameterDemo {
int width; public static void main(String[] args) {
// Constructor // Create a Rectangle object
Rectangle(int l, int w) { Rectangle rect = new Rectangle(10, 5);
length = l;
width = w; // Display original dimensions
} [Link]("Original Rectangle:");
// Method to display rectangle dimensions [Link]();
void displayDimensions() {
[Link]("Length: " + length + ", Width: " + width); // Create AreaCalculator object
} AreaCalculator calc = new AreaCalculator();
}
// AreaCalculator class with method that takes Rectangle object // Pass object as parameter to calculate area
class AreaCalculator { [Link](rect);
// Method that takes a Rectangle object as parameter
void printArea(Rectangle r) { // Modify the rectangle by passing object to another method
int area = [Link] * [Link]; [Link](rect, 5, 3);
[Link]("Area of Rectangle: " + area);
} // Display new dimensions
// Method to modify rectangle dimensions [Link]("Modified Rectangle:");
void enlargeRectangle(Rectangle r, int extraLength, int extraWidth) { [Link]();
[Link] += extraLength;
[Link] += extraWidth; // Calculate new area
[Link]("Rectangle enlarged."); [Link](rect);
} }
} }
Example Program for Objects as Parameters
Expected Output: Explanation of above Program :
Original Rectangle:
Length: 10, Width: 5 •Object as Parameter: The Rectangle object is passed to
methods in AreaCalculator.
Area of Rectangle: 50
•Accessing Fields: The printArea() method accesses the
Rectangle enlarged.
length and width of the Rectangle.
Modified Rectangle:
•Modifying Object: The enlargeRectangle() method
Length: 15, Width: 8 modifies the original object. Since the reference is passed,
Area of Rectangle: 120 changes reflect outside the method.
Argument Passing

 Argument passing refers to how data is sent from one part of a program (usually the main() method) to a method when it's
called.
 In Java, this happens when you call a method and pass values (arguments) to it. These values are received by parameters
in the method.

 Two common mechanisms in programming:


 Pass-by-value
 Pass-by-reference
But Java uses only one: ✅ Pass-by-value
Pass-by-Value in Java
•Important Rule: Java always passes arguments by value.
•This means:
•A copy of the variable is sent to the method.
•For primitive types: value is copied.
•For objects: reference (memory address) is copied.

Note:
You can change object fields, but not the reference itself.
Primitives – Pass-by-Value Example
public class PrimitiveExample {

public static void changeValue(int num) {


num = 100; // Change the local copy Explanation:
}
•x is a primitive.
public static void main(String[] args) { •A copy of x (value 50) is passed.
•Inside the method, changes affect the copy only.
int x = 50;
changeValue(x);
[Link]("Value of x after
changeValue: " + x);
}
}
Output
Value of x after changeValue: 50
Objects – Reference Passed by Value Example
class Box {
int value;
}
public class ObjectExample { Explanation:
•The reference to box is passed by value.
public static void modify(Box b) {
•Inside modify(), both b and box point to the same object.
[Link] = 200; // Modify the object's field •Modifying [Link] changes the original object's value.
}
public static void main(String[] args) { The object reference is copied, but both refer to the same object, so
changes inside the method affect the original object.
Box box = new Box();
[Link] = 50;
modify(box);
[Link]("Value of [Link] after
modify: " + [Link]);
}
}
Output:
Value of [Link] after modify: 200
Object Reference Argument Passing (Reassigning
Reference)
class Box { Output:
int value; Value of [Link] after reassign: 100
}
public class ReassignExample {
public static void reassign(Box b) {
b = new Box(); // New object created locally
Explanation
[Link] = 999;
•The reference is passed by value.
} •Reassigning b creates a new object.
public static void main(String[] args) {
•The original reference box is not affected.
•Reassigning b inside the method does not affect the original box
Box box = new Box(); reference.
[Link] = 100;
reassign(box);
[Link]("Value of [Link] after
reassign: " + [Link]);
}
}
Example with List (Object Modification)
Output:
import [Link];
List after addToList: [Java]
import [Link];
public class ListExample {
public static void addToList(List<String> list) {
[Link]("Java"); Explanation:
} •The reference to myList is passed.
public static void main(String[] args) { •Adding an item modifies the actual list object.
List<String> myList = new ArrayList<>();
addToList(myList);
[Link]("List after addToList: " +
myList);
}
}
Summary Table
RETURNING OBJECTS

What Does Returning an Object Mean?


Method Signature for Returning Objects
In Java ,returning an object means returning a
reference to that object.
 Methods can return any data type, including
objects. public ClassName methodName() {
 The caller gets access to the same object in
memory.
// method body
return objectReference;
Why return objects?
}
 To send complex data structures or
multiple values.
 To enable method chaining and  The return type is the class name of the object being
modular design.
returned.
 To create and pass around reusable
data models. Must return an object reference of that type or a subtype.
Program that demonstrates returning objects from a method
// Define the Person class public static Person createPerson() {
class Person { return new Person("Alice");
String name; }

// Constructor to initialize name public static void main(String[] args) {


Person(String name) { // Call method and store returned Person object
[Link] = name; Person person = createPerson();
}
} // Access and print the name field of the returned
// Main class with method that returns a Person object object
public class ReturnObjectDemo { [Link]("Person's name: " +[Link]);
// Method that creates and returns a new Person }
object }

OUTPUT: Person's name: Alice


RECURSION

Java Support for Recursion: Recursion is the attribute that allows a method to
call itself. A method that calls itself is said to be recursive.
🔹 When a method calls itself, new local variables and parameters are allocated
storage on the stack, and the method code is executed with these new variables
from the start.
🔹 As each recursive call returns, the old local variables and parameters are
removed from the stack, and execution resumes at the point of the call inside the
method.
🔸 Limitation: Recursive versions may execute a bit slowly than the iterative
equivalent because of the overhead of the additional method calls.
🔸 Advantage: Clear and simpler version of iterative algorithms.
When to use recursion?
 The problem can be divided into similar sub-problems
 The depth is manageable (not too many recursive calls)
 Code clarity is more important than performance

Real-World Uses of Recursion


 File system traversal
 Backtracking (e.g., solving mazes, puzzles)
 Algorithms (e.g., quicksort, mergesort)
 Tree/graph algorithms (DFS)
Example: Factorial of number

public class RecursionDemo { HOW IT WORKS:?


// Recursive method to calculate factorial
factorial(5)
public static int factorial(int n) {
if (n == 0) { → 5 * factorial(4)

return 1; // Base case → 4 * factorial(3)


} else { → 3 * factorial(2)
return n * factorial(n - 1); // Recursive → 2 * factorial(1)
call
→ 1 * factorial(0)
}
} → returns 1
public static void main(String[] args) { Then it starts returning:
int number = 5; factorial(1) = 1 * 1 = 1
int result = factorial(number);
factorial(2) = 2 * 1 = 2
[Link]("Factorial of " + number
+ " is: " + result); factorial(3) = 3 * 2 = 6
} factorial(4) = 4 * 6 = 24
} factorial(5) = 5 * 24 = 120
Output: Factorial of 5 is: 120
ACCESS CONTROL

Access control is a mechanism to restrict or allow access to classes,


methods, variables, and constructors in a Java program. It helps enforce
encapsulation, one of the core principles of object-oriented programming,
by controlling who can see or modify certain parts of your code.
Why is Access Control Important?
 Protects data: Keeps sensitive data safe from accidental or
unauthorized modification.
 Encapsulation: Hides internal details and exposes only what’s
necessary.
 Organizes code: Controls access between different parts of your
program or different programs.
ACCESS MODIFIERS IN JAVA

Java provides four main access modifiers that define


visibility.
Access Control and visibility
•Public: When a member of a class is modified by public, then that member can be
accessed by any other code.
•Example: main() has always been preceded by the public modifier. It is called by
code that is outside the program i.e. by Java run-time system.
•Private: When a member of a class is specified as private, then that member can
only be accessed by other members of its class.
•Default: When no access modifier is used, then by default the member of a class is
public within its own package, but cannot be accessed outside of its package.
•Syntax: An access modifier precedes the member’s type specification i.e.
access_modifier datatype identifier;
• e.g: private int i;
Example Java Program Using Access Modifiers // Method to access private members inside the
class
// File: [Link] public void accessPrivate() {
package mypackage; [Link]("Accessing private
// Class demonstrating access modifiers variable: " + privateVar);
public class AccessModifierDemo { privateMethod();
public int publicVar = 10; // Accessible everywhere }
private int privateVar = 20; // Accessible only within this class }
protected int protectedVar = 30; // Accessible in same package Output:
and subclasses 10
int defaultVar = 40; // Default access: same package only 30
40
public void publicMethod() { // Public method
Public method called
[Link]("Public method called");
Protected method called
} Default method called
private void privateMethod() { // Private method Accessing private variable: 20
[Link]("Private method called"); Private method called
}
Explanation:
protected void protectedMethod() { // Protected method •publicVar prints 10 (public: accessible everywhere)
•protectedVar prints 30 (protected: accessible in same package)
[Link]("Protected method called"); •defaultVar prints 40 (default/package-private: accessible in same
} package)
•publicMethod() prints "Public method called"
void defaultMethod() { // Default method •protectedMethod() prints "Protected method called"
[Link]("Default method called"); •defaultMethod() prints "Default method called"
•accessPrivate() method prints "Accessing private variable: 20" and calls
} the private method which prints "Private method called"
Accessing from another class in the same package
package mypackage;
public class SamePackageAccess {
Output:
public static void main(String[] args) { 10
AccessModifierDemo obj = new AccessModifierDemo();
[Link]([Link]); // Accessible 30
[Link]([Link]); // Accessible (same package)
[Link]([Link]); // Accessible (same package) 40
// [Link]([Link]); // NOT accessible (private)
[Link](); // Accessible Public method called
[Link](); // Accessible (same package)
[Link](); // Accessible (same package)
Protected method called
// [Link]();
[Link]();
// NOT accessible (private)
// Access private member via public method
Default method called
} Accessing private variable: 20
What happens step-by-step:
}
•Prints value of publicVar → 10
Private
•Prints value of protectedVar → 30 method called
•Prints value of defaultVar → 40
•Calls publicMethod() → prints "Public method called"
•Calls protectedMethod() → prints "Protected method called"
•Calls defaultMethod() → prints "Default method called"
•Calls accessPrivate() which internally accesses privateVar and calls
privateMethod(), printing:
•"Accessing private variable: 20"
•"Private method called"
Summary:
Static Keyword
•It is possible to create a member that can be used by itself, without reference to a
specific instance. To create such a member, precede its declaration with the keyword
static.
•When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
•Both methods and variables can be declared as static.
The most common example of a static member is main(). main() is declared as static
because it must be called before any objects exist.
•Static Instance variables: Instance variables declared as static are global variables.
When objects of its class are declared, no copy of a static variable is created.
Instead, all instances of the class share the single copy of static variable.
Static keyword contd..

Static Methods:
Methods declared as static have several restrictions:
[Link] can only directly call other static methods of their class.
[Link] can only directly access static variables of their class.
[Link] cannot refer to this or super in any way.
Static Block:
If you need to do computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded.
Note:
Static methods and variables can be used independently of any object outside the
defining class.
ToGeneral
do so, you need only specify the name of the class followed by the dot operator.
form:
[Link]();
Example:
// Demonstrate static variables, methods, Output
and blocks.
class UseStatic {
Static block initialized.
static int a = 3;
static int b;
// Static data
x = 42
static void meth(int x) { // Static method a=3
[Link]("x = " + x);
[Link]("a = " + a); b = 12
[Link]("b = " + b);
}
static { // Static block
[Link]("Static block
initialized.");
b = a * 4;
Explanation:
}
public static void main(String[] args) {
meth(42);
}
Key Concepts from the Example:
•Static variables like a and b are shared across all uses of the class.
}
•Static methods like meth() can be called without creating an object.
•The static block runs once, initializing static data before any method runs.
A static variable can be accessed using the class name and the dot operator —
This is how Java gives us a controlled version of global variables and methods.

Example:
class StaticDemo { Output:
static int a = 42; // Static a = 42
data b = 99
static int b = 99;
static void callme() { // Static
method
[Link]("a = " + a); What this does:
[Link] class has:
} •Two static variables: a = 42, b = 99
} •One static method: callme(), which
class StaticByName { prints the value of a
public static void main(String[] args) { [Link] class has:
•main() method that:
[Link](); •Calls [Link]() →
// Call static method prints a = 42
[Link]("b = " + •Accesses StaticDemo.b directly
→ prints b = 99
StaticDemo.b); // Access static variable
}
}
Final Keyword
•Java provides several modifiers to control access and behavior.
•The final keyword is used to prevent modification.
•It can be applied to:
1. Final Variables
 Variables •A variable marked final cannot be Must bereassigned after
 Methods initialization.
 Classes •It becomes a constant.
• initialized:
• At declaration, or
• In a constructor (if it's an instance variable)
Example:
2. A method declared as final cannot be overridden by final int MAX = 100;
subclasses.
•Used to preserve implementation in inheritance.
Example: 3. Classes
class Parent {
•A final class cannot be extended.
final void show() { •Prevents inheritance completely.
[Link]("Can't be overridden");
} •Example:
} final class Vehicle {
// Cannot have subclasses
}
Example: Using final with Variable, Method, and Class

// Final class cannot be inherited


final class Constants {
// Final variable (constant)
public static final double PI = 3.14159;
// Final method cannot be overridden
public final void showConstant() {
[Link]("The value of PI is: " + PI); Explanation
•The main() method creates an object c of class Constants.
}
•It calls showConstant(), which prints the value of the final variable
} PI.
public class FinalExample { •Since PI is a static final variable, it's treated like a constant.
•There is no error as long as you don’t try to reassign PI.
public static void main(String[] args) {
Constants c = new Constants();
[Link]();
// Trying to change final variable (uncomment
to see error)
// [Link] = 3.14; // ❌ Error: cannot assign a value
to final variable 'PI'
}
}
Output:
The value of PI is: 3.14159
NESTED AND INNER CLASSES

•In java, it is possible to define a class within another class; such classes are known as
nested classes. The scope of a nested class is bounded by the scope of its enclosing
class.
•A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members of
the nested class.
•It is also possible to declare a nested class that is local to a block.
•There are two types of nested classes:
[Link] nested class
[Link]-static nested class / inner class
1. Static Nested Class:
 A static nested class is one that has the static modifier applied.
 Because it is static, it must access the non-static members of its enclosing class
through an object.
 That is, it cannot refer to non-static members of its enclosing class directly.

2. Inner Class:
 An inner class is a non-static nested class.
 It has access to all of the variables and methods of its outer class and may refer to them
directly, just like other non-static members.
 Members of the inner class are known only within the scope of the inner class and may not
be used by the outer class.
Example program demonstrating both static nested class and inner class:

class OuterClass { public class TestNestedInner {


int outerVar = 10; public static void main(String[] args) {
static int staticOuterVar = 20; // Create object of static nested class without outer class object
// Static Nested Class [Link] staticNestedObj = new
static class StaticNested { [Link]();
void display() { [Link]();
// Can access static members of outer class directly
// Create outer class object
[Link]("Static nested accessing
staticOuterVar: " + staticOuterVar); OuterClass outer = new OuterClass();
} // Create inner class object using outer class object
} [Link] innerObj = [Link] Inner();
// Inner Class (Non-static nested class) [Link]();
class Inner { }
void display() { }
// Can access both static and non-static members of Output:
outer class
Static nested accessing staticOuterVar: 20
[Link]("Inner class accessing outerVar: "
+ outerVar); Inner class accessing outerVar: 10
[Link]("Inner class accessing Inner class accessing staticOuterVar: 20
staticOuterVar: " + staticOuterVar); Explanation:
•StaticNested class can access only static members of the outer class.
} •Inner class can access both static and non-static members.
} •You can instantiate static nested class without creating an instance of the outer class.
•To instantiate inner class, you need an instance of the outer class.
}
Review Questions:

1. Explain Java support for compile-time polymorphism by taking suitable programming example.
2. With a program, explain the effect of automatic type conversion in method overloading.
3. Explain constructor overloading with suitable class definition and program.
4. Explain with suitable program:
a) Objects as method parameters
b) Objects as constructor parameters
5. Explain passing of primitive types and passing of objects as arguments to methods with suitable programs.
6. Explain returning of objects from methods with a program.
7. Explain how recursion is implemented in Java?
What are the benefits of recursion in programming?
8. Explain with a program, Java support for encapsulation through visibility modifiers.
9. Explain the different roles of keyword static with programs.
10. Explain different roles of keyword final with programs.
11. Explain the role of static nested classes and inner classes with programs.
12. Develop a recursive version of generating, storing, and displaying the Fibonacci series

You might also like