0% found this document useful (0 votes)
23 views

P in JAVA M3

java 3rd module notes for beginners and 3rd year btech students

Uploaded by

nihalnagekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

P in JAVA M3

java 3rd module notes for beginners and 3rd year btech students

Uploaded by

nihalnagekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Programming in JAVA

Programming in Java
Course Code 21CS652 CIE Marks 50
Teaching Hours/Week (L: T: P: S) (3:0:0:0) SEE Marks 50
Total Hours of Pedagogy 40 hours Theory Total Marks 100
Credits 03 Exam Hours 03
Course Learning Objectives
CLO 1. Learn fundamental features of object-oriented language and JAVA.
CLO 2. To create, debug and run simple Java programs.
CLO 3. Learn object-oriented concepts using programming examples.
CLO 4. Study the concepts of importing packages and exception handling mechanism.
CLO 5. Discuss the String Handling examples with Object Oriented concepts.
Teaching-Learning Process (General Instructions)
These are sample Strategies, which teachers can use to accelerate the attainment of the various course outcomes.
1. Lecturer method (L) need not to be only a traditional lecture method, but alternative effective teaching methods could be
adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning) Learning in the class.
4. Ask at least three HOT (Higher order Thinking) questions in the class, which promotes critical thinking.
5. Adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop design thinking skills such as the ability
to design, evaluate, generalize, and analyze information rather than simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem with different circuits/logic and encourage the students to come up with their
own creative ways to solve them.
8. Discuss how every concept can be applied to the real world - and when that's possible, it helps improve the students'
understanding.
Module-3:
Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference Variables, Introducing Methods,
Constructors, The this Keyword, Garbage Collection, The finalize( ) Method, A Stack Class.
A Closer Look at Methods and Classes: Overloading Methods, Using Objects as Parameters, A Closer Look at Argument Passing,
Returning Objects, Recursion, Introducing Access Control, understanding static, Introducing final, Arrays Revisited.
Inheritance: Inheritance, Using super, Creating a Multilevel Hierarchy, When Constructors Are Called, Method Overriding.
Textbook 1: Ch 6, Ch 7.1-7.9,Ch 8.1-8.5
Teaching-Learning Process Chalk and Talk, PowerPoint Presentation RBT Level: L1, L2, L3

Textbooks
1. Herbert Schildt, Java The Complete Reference, 7th Edition, Tata McGraw Hill, 2007. (Chapters 2, 3, 4, 5, 6,7, 8, 9,10, 12,15)
Reference Books:
1. Mahesh Bhave and Sunil Patekar, "Programming with Java", First Edition, Pearson
Education,2008, ISBN:9788131720806.
2. Rajkumar Buyya,SThamarasiselvi, xingchen chu, Object oriented Programming with java, Tata
McGraw Hill education private limited.
3. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 1


Introduction to Classes
In Java, a class is a blueprint or template for creating objects. It defines the structure and behavior of objects that will be
created based on it. A class contains data members (fields) and methods (functions) that define the characteristics and
behavior of the objects.
Here's a simple example of a class in Java:
// Defining a simple class named"Person"
class Person {
// Data members (fields)
String name;
int age;
// Methods
void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
public class test {
public static void main(String[] args) {
Person person2 = new Person();
// Accessing and modifying data members
person2.name = "Alice";
person2.age = 30;
// Calling methods on objects
person2.sayHello(); // Output: Hello, my name is Alice and I am 30 years old.

}
}
Explanation:
1. Class Definition (`Person`):
- We define a class named `Person` using the `class` keyword. It has two data members (`name` and `age`) and one
method (`sayHello()`).
- Data members (`name` and `age`) are variables that store information about the objects of the class.
- The method `sayHello()` is a function that defines the behavior of the objects.
2. Creating Objects (`person1` and `person2`):
- We create objects of the class `Person` using the `new` keyword. Each object represents a specific person with its
own set of data members.
3. Accessing Data Members:
- We access and modify the data members (`name` and `age`) of the objects using the dot notation
(`objectName.dataMember`).
4. Calling Methods on Objects:
- We call the method `sayHello()` on the objects using the dot notation (`objectName.method()`). Each object calls the
method with its own data members.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 2


Process of Object Creation
What are objects with example the use of the “ new ” keyword in java ?
We use the new keyword in Java to instantiate a class via allocating the required memory for a new object. The new
keyword returns a reference to that memory post-object creation. Sometimes, we can make use of the new keyword in Java
to create the array objects.
“The new keyword in Java instantiates a class by allocating desired memory for an associated new object. It then returns a reference to
that memory. Many times, the new keyword in Java is also used to create the array object.”

The process of creating an instance of a class has to follow the following steps given below:
• Declaration
• Instantiation
• Initialization
Now let us understand them one by one.
Declaration
In order to create an object, we start by declaring a variable of that class type. This variable can be used to refer to that newly
created object. Following is the syntax for declaration, along with an example:
Syntax: className varName;
Example: Box myBox;
The defined variable in the state currently references no object and is just understood as the variable name, myBox of data-
type Box.
Instantiation
After variable declaration, we need to acquire an actual, physical copy of that object (memory reference) and assign it to
the variable. The new keyword instantiates a class by allocating memory for a new object and returning a reference to that
memory. This dynamic memory allocation happens at the run-time.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the
appropriate type, like:
Syntax: className varName = new className();
Example: Box mybox = new Box();
Now let us concentrate on the class Box prototype before jumping on
dynamic allocation of memory.
class Box{
double width;
double height;
double depth;
}
In the diagram given :
• We are declaring a variable myBox of data type Box. We have not yet assigned a memory reference to it.
• In the second statement, the new keyword instantiates the class by allocating memory to its new object and returns a
reference to that memory to the myBox variable, thereby initializing it.
Key Points:
• The key phrase “instantiating a class” can be described as “creating an object.” When we create an object, we are
actually creating an “instance” of the class.
• The memory reference returned by the new operator can be directly used in an
expression, as shown below. It doesn't need to be assigned to a variable of
appropriate data type.
double height = new Box().height;
• Since arrays are objects in Java, hence while instantiating arrays, we use the new
operator. For example:

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 3


int arr[] = new int[5];
• We need to know that Java’s primitive types are never implemented as objects and are rather implemented as
“normal” variables, as this can lead to good efficiency.
Note:
The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are
creating an "instance" of a class, therefore "instantiating" a class.
The new operator requires exactly one postfix parameter: a call to the class constructor. A constructor defines what occurs
when an object of a class is created. Constructors are an important part of all classes and have many significant
attributes. In the below example, we will use the default constructor.
Initialization
All classes have at least one constructor. If a class does not explicitly declare any, the online Java compiler automatically
provides a no-argument constructor, called the default constructor.
1. Default Constructor:
A default constructor is a constructor that takes no arguments and initializes the object's attributes with default values. In
Java, if you don't provide any constructors explicitly, the compiler automatically adds a default constructor for you.
2. Parameterized Constructor:
A parameterized constructor is a constructor that takes arguments and initializes the object's attributes with the provided
values. Here's the necessary Java code to implement the `Box` class with both a default and parameterized constructor:
public class Box {
double width;
double height;
double depth;
// Default Constructor
public Box() {
width = 1.0; // Default width
height = 1.0; // Default height
depth = 1.0; // Default depth
}
// Parameterized Constructor
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
// Getters and setters (not shown for brevity)
}
Explanation:
- In the `Box` class, we declared three attributes: `width`, `height`, and `depth`.
- The default constructor initializes the attributes with default values of `1.0`.
- The parameterized constructor takes three arguments (width, height, and depth) and uses them to initialize the
object's attributes.
- In the `main` method, we demonstrate object initialization using both the default and parameterized constructors.
- When `defaultBox` is created using the default constructor, its attributes will have default values of `1.0`.
- When `paramBox` is created using the parameterized constructor, its attributes will be set to the provided values
`5.0`, `3.0`, and `2.0`.
By providing both constructors, you can initialize objects either with default values or with custom values based on your
requirements.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 4


public class Main {
public static void main(String[] args) {
// Initializing using the default constructor
Box defaultBox = new Box();
System.out.println("Default Box: Width = " + defaultBox.width + ", Height = " +
defaultBox.height + ", Depth = " + defaultBox.depth);
// Initializing using the parameterized constructor
Box paramBox = new Box(5.0, 3.0, 2.0);
System.out.println("Parameterized Box: Width = " + paramBox.width + ", Height = "
+ paramBox.height + ", Depth = " + paramBox.depth);
}
}
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an assignment takes place. For example, what
do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object
referred to by b1. That is, you might think that b1 and b2 refer to separate and
distinct objects. However, this would be wrong. Instead, after this fragment
executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any
part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object
through b2 will affect the object to which b1 is referring, since they are the same object. This situation is depicted
Process of Creating an Array Object
Let us understand with the below code how we can implement the new keyword in Java and create an array object
using the new keyword.
Code:
public class ArrayCreation {
public static void main(String[] args) {
int arr[] = new int[5];
System.out.println("The Array length is : " + arr.length);
}
}
Output:
The Array length is: 5
Explanation:
In the code above, we are using the new keyword to create the array object of size five in the heap memory.
The memory reference is returned by the new keyword and is stored in the arr variable.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 5


Adding a Method
what are parameterized methods and non-parameterized methods
Classes usually consist of two things: instance variables and methods. The topic of methods is a large one because Java gives
them so much power and flexibility.
Parameterized methods (also known as methods with parameters) and non-parameterized methods (also known as methods
without parameters) are two types of methods in programming languages like Java. These methods differ in their ability to
accept input data (arguments) when they are called and perform specific operations based on that input.
Parameterized Methods:
- Parameterized methods are methods that accept input parameters (arguments) when they are called. These parameters
provide the necessary data for the method to perform its operations or calculations.
- The input parameters allow you to pass values from the calling code to the method, enabling dynamic behavior and
reusability of the method with different input values.
- Parameterized methods are useful when you want to perform operations that depend on specific data or when you want to
customize the behavior of the method based on the inputs provided.
Here's an example of a parameterized method:

// Method that takes parameters and sets the dimensions of the box
public void setDimensions(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
`setDimensions()` method: This method takes three parameters (`width`, `height`, and `depth`) and sets the dimensions of
the box based on the provided values.
Non-Parameterized Methods:
- Non-parameterized methods are methods that do not accept any input parameters when they are called. They perform
their operations without requiring any additional data from the calling code.
- Non-parameterized methods are useful when you have fixed behaviors or calculations that do not depend on external
input. These methods are often used for simple operations or utility functions.
Here's an example of a non-parameterized method:
// Method that does not take parameters
public double calculateVolume() {
return width * height * depth;
}
`calculateVolume()` method: This method calculates the volume of the box using the formula `volume = width * height *
depth`. It does not take any parameters and returns the calculated volume.
In summary, parameterized methods accept input parameters for dynamic behavior, while non-parameterized
methods perform fixed operations without requiring any additional data. Both types of methods are essential
in programming and serve different purposes based on the requirements of the code.
In the modified `Box` class, we have added two new methods: With these new methods added to the `Box` class, you can
now use them in your `Main` class to perform volume calculations and set different dimensions for the boxes.
public class Main {
public static void main(String[] args) {
// Initializing using the default constructor
Box defaultBox = new Box();
System.out.println("Default Box: Volume = " + defaultBox.calculateVolume());

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 6


// Initializing using the parameterized constructor
Box paramBox = new Box(5.0, 3.0, 2.0);
System.out.println("Parameterized Box: Volume = " + paramBox.calculateVolume());
// Set new dimensions for paramBox using the setDimensions method
paramBox.setDimensions(3.5, 4.0, 2.5);
System.out.println("Updated Box: Volume = " + paramBox.calculateVolume());
}
}
In the `Main` class, we call the `calculateVolume()` method on both the defaultBox and paramBox objects to calculate and
display their volumes. Then, we use the `setDimensions()` method to update the dimensions of the paramBox object and
calculate its volume again.

Garbage Collection
Write a short note on Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed
and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be
manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically.
The technique that accomplishes this is called garbage collection. It works like this: when no references to an object exist, that
object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need
to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during the execution of your program. It
will not occur simply because one or more objects exist that are no longer used. Furthermore, different Java run-time
implementations will take varying approaches to garbage collection, but for the most part, you should not have to think
about it while writing your programs

The finalize( ) Method


What is The `finalize()` method in Java
The `finalize()` method in Java is provided by the `Object` class, the superclass of all classes in Java. It allows an object to
perform cleanup actions just before it is garbage collected. When an object becomes eligible for garbage collection, the
`finalize()` method is called by the JVM before reclaiming the object.
The method's signature is: `protected void finalize() throws Throwable {}`
However, the `finalize()` method has some considerations and limitations. Its exact timing of execution is uncertain, and
there is no guarantee that it will be called for every object. Additionally, its use can introduce overhead to the garbage
collection process. Due to these issues, the `finalize()` method has been deprecated in Java 9, and modern Java development
prefers alternative mechanisms like try-with-resources or the `AutoCloseable` interface for resource cleanup.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 7


A Closer Look at Methods and Classes
Method Overloading
Two or more methods within the same class that share the same name, but their parameter declarations (type and/or
number) are different. Method Overloading is one of the ways that Java supports polymorphism.
Java uses the type and/or number of arguments to determine which version of the overloaded method to actually call. It is to
be noted that return type alone is insufficient to distinguish two versions of a method.
In some cases, Java’s automatic type conversions can play a role in overload resolution. It is also also possible to overload
constructors.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a * a;
}
}
class Main {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
double result;
ob.test();
ob.test(10, 20);
result = ob.test(123.25); // this will invoke test(double)
System.out.println("Result: " + result);
result = ob.test(i); // this will invoke test(double)
System.out.println("Result: " + result);
}
}
As you can see, this version of OverloadDemo does not define test(int). Therefore, when test( ) is called with an
integer argument inside Overload, no matching method is found. However, Java can automatically convert an
integer into a double, and this conversion can be used to resolve the call. Therefore, after test(int) is not found, Java
elevates i to double and then calls test(double). Of course, if test(int) had been defined, it would have been called instead. Java
will employ its automatic type conversions only if no exact match is found.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 8


Overloading Constructors
class Box {
double width;
double height;
double depth;
Box() {
width = 1;
height = 1;
depth = 1;
}
Box(double side) {
width = side;
height = side;
depth = side;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
public class Main {
public static void main(String[] args) {
// Create objects using different constructors
Box box1 = new Box(); // Default constructor
Box box2 = new Box(5); // Constructor with one parameter
Box box3 = new Box(2.5, 3, 4); // Constructor with three parameters
// Calculate and print volumes of the boxes
System.out.println("Volume of box1: " + box1.volume());
System.out.println("Volume of box2: " + box2.volume());
System.out.println("Volume of box3: " + box3.volume());
}
}

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 9


Using Objects as Parameters
In Java, you can pass objects as parameters to methods just like you pass primitive data types. When you pass an object as a
parameter, you are essentially passing a reference to that object, allowing the method to access and modify its properties.
Here's an explanation with an example:
Let's consider a simple `Rectangle` class that represents a rectangle with width and height, Now, let's create another class
`Main` with a method `doubleArea()` that takes an object of the `Rectangle` class as a parameter.
class Rectangle {
double width;
double height;
Rectangle(double w, double h) {
width = w;
height = h;
}
double area() {
return width * height;
}
}
public class Main {
static void doubleArea(Rectangle r) {
r.width *= 2;
r.height *= 2;
}
public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 3);
System.out.println("Original area: " + rect.area());
// Passing the Rectangle object as a parameter
doubleArea(rect);
System.out.println("Area after doubling width and height: " + rect.area());
}
}
In this example:
- We have a class with a constructor to initialize width and height, and a method `area()` to calculate the area of the rectangle.
- In the `Main` class, we have a static method `doubleArea()` that takes a `Rectangle` object as a parameter.
- Inside the `doubleArea()` method, we double the width and height of the rectangle passed as a parameter.
- In the `main()` method, we create a `Rectangle` object named `rect` with width 5 and height 3.
- We call the `doubleArea()` method and pass the `rect` object as a parameter.
- After calling the method, we print the area of the rectangle to see the effect of doubling the width and height.

When you pass an object as a parameter, you're passing a reference to the object, so any changes made to the object within
the method will affect the original object outside the method. In this example, the `doubleArea()` method modifies the width
and height of the `Rectangle` object, and these modifications are reflected in the original object `rect`.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 10


Give an example to compare objects for equality using a Test class with instance variables and a method equals()
The below given program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
As you can see, the equals( ) method inside Test compares two objects for equality and returns the result. That is, it compares
the invoking object with the one that it is passed. If they contain the same values, then the method returns true. Otherwise, it
returns false. Notice that the parameter o in equals( ) specifies Test as its type. Although Test is a class type created by the
program, it is used in just the same way as Java’s built-in types. One of the most common uses of object parameters involves
constructors. Frequently, you will want to construct a new object so that it is initially the same as some existing object. To do
this, you must define a constructor that takes an object of its class as a parameter.
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if (o.a == a && o.b == b)
return true;
else
return false;
}
}
class Main {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
One can use the same technique to allow one object to initialize another.

A Closer Look at Argument Passing


CALL BY VALUE CALL BY REFERENCE
• The value of the argument is copied into the formal • A reference to an argument (not the value of the
parameter of the method. argument) is passed to the parameter. Inside the
• Changes made to the parameter will not affect the method, this reference is used to access the actual
argument used to call the method. argument specified in the call.
• Simple types (int, float, char, etc) are passed as call • Changes made to the parameter will affect the
by value argument used to call the method.
• Objects are passed as call by reference.

In programming languages like Java, when passing arguments to methods, there are two common ways that parameters can
be passed: "call by value" and "call by reference". Let's discuss each of these concepts along with an example:

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 11


1. Call by Value:
- In call by value, a copy of the actual parameter's value is passed to the method. This means that any changes made to the
parameter within the method do not affect the original value of the argument.
- Primitive data types (e.g., `int`, `double`, `char`, etc.) are passed by value.
- Changes made to the parameter within the method are confined to the method's scope and do not affect the original
variable outside the method.
Example:
public class CallByValueExample {
static void modifyValue(int x) {
x = x * 2; // Modify the value of x
System.out.println("Inside the method: x = " + x);
}
public static void main(String[] args) {
int num = 5;
System.out.println("Before calling the method: num = " + num);
modifyValue(num); // Call the method with num as argument
System.out.println("After calling the method: num = " + num);
}
}
Output: Before calling the method: num = 5; Inside the method: x = 10; After calling the method: num = 5
In this example, the value of `num` remains unchanged outside the `modifyValue()` method because it was passed by value.
2. Call by Reference:
- In call by reference, a reference (memory address) of the actual parameter is passed to the method. This allows the
method to directly access and modify the original data.
- Objects, arrays, and non-primitive types in Java are passed by reference.
- Changes made to the parameter within the method are reflected in the original variable outside the method.
Example:
class MyClass {
int value;
MyClass(int value) {
this.value = value;
}
}
public class CallByReferenceExample {
static void modifyObjectValue(MyClass obj) {
obj.value = obj.value * 2; // Modify the value of obj
System.out.println("Inside the method: obj.value = " + obj.value);
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println("Before calling the method: myObj.value = " + myObj.value);
modifyObjectValue(myObj); // Call the method with myObj as argument
System.out.println("After calling the method: myObj.value = " + myObj.value);
}
}

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 12


Output: Before calling the method: myObj.value = 5; Inside the method: obj.value = 10; After calling the method: myObj.value = 10
In this example, the value of `myObj.value` is modified inside the `modifyObjectValue()` method because it was passed by
reference.

Returning Objects
A method can return any type of data, including class types that you create. For example, in the following program, the
incrByTen( ) method returns an object in which the value of a is ten greater than it is in the invoking object.

class Rectangle {
double length; double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double calculateArea() {
return length * width;
}
}
public class ReturnObjectExample {
static Rectangle createRectangle(double length, double width) {
return new Rectangle(length, width);
}
public static void main(String[] args) {
Rectangle rect = createRectangle(5, 3);
double area = rect.calculateArea();
System.out.println("Area of the rectangle: " + area);
}
}
In the provided example, a `Rectangle` class is defined to model rectangles, characterized by their length and width
attributes. The `Rectangle` class incorporates a constructor responsible for initializing these attributes, alongside a
`calculateArea()` method designed to compute the area of the rectangle based on its dimensions. Additionally, a
`ReturnObjectExample` class is introduced, featuring a static method named `createRectangle()`. This method accepts
parameters denoting the length and width of the rectangle and returns a new instance of the `Rectangle` class, initialized
with the specified dimensions. Within the `main()` method of the program, the `createRectangle()` method is invoked to
instantiate a new rectangle object. Subsequently, the returned rectangle object is utilized to calculate and display its area,
exemplifying the concept of returning objects from methods and utilizing them within the program flow.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 13


Recursion
Recursion in Java refers to a programming technique where a method calls itself to solve a problem. It is particularly useful
for solving problems that can be broken down into smaller, similar sub-problems. Let's illustrate recursion with an example:
Consider the problem of calculating the factorial of a non-negative integer `n`. The factorial of a number `n`, denoted as `n!`,
is the product of all positive integers less than or equal to `n`. Mathematically, `n! = n * (n-1) * (n-2) * ... * 1`.
Here's how you can implement factorial calculation using recursion in Java:
public class RecursionExample {
// Recursive method to calculate factorial
static int factorial(int n) {
// Base case: if n is 0 or 1, return 1
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: n! = n * (n-1)!
else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int num = 5;
int result = factorial(num);
System.out.println("Factorial of " + num + " is: " + result);
}
}
In the provided code snippet, a class named `RecursionExample` is defined, which encapsulates a static method named
`factorial(int n)`. This method is designed to compute the factorial of a given integer `n`. Within the `factorial` method, two
distinct cases are handled. Firstly, there is a base case where if `n` equals 0 or 1, the method returns 1 since the factorial of 0
or 1 is 1. Secondly, a recursive case is established wherein the `factorial` method is invoked with the argument `n-1` until
reaching the base case. In the `main` method of the program, the `factorial` method is invoked with an integer value `num`,
set to 5 in this instance, and the resulting factorial value is printed.

display array recursively


public class DisplayArrayRecursively {
static void displayArray(int[] arr, int index) {
if (index == arr.length) {
return;
}
System.out.print(arr[index] + " ");
displayArray(arr, index + 1);
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println("Array elements:");
displayArray(array, 0); // Call the recursive method to display array elements
}}

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 14


Introducing Access Control
Access specifiers in Java provide a means for containing the name space and scope of variables and methods.
Access Modifiers in java : There are two types of modifiers in java: access modifiers and non-access modifiers. The access
modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java
access modifiers:
private can be accessed only within the class and not outside it
no modifier can be accessed outside the class in which they are declared but only by classes (including subclasses) within the
(default) same package
can be accessed outside the class in which they are declared within the same package but only by subclasses
protected
outside the package
public can be accessed anywhere

1) Private access modifier: The private access modifier is accessible only within class.
Example of private access modifier: In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from outside the class, so there is compile time
error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");} }
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
} }
2) Default access modifier: If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
Example of default access modifier: Given code has two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
3) Protected access modifier: The protected access modifier is accessible within package and outside the package but

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 15


through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Example of protected access modifier: In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
} }
Output: Hello
4) public access modifier: The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier :
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
Output:Hello

Difference between constructor and method in java


Java Constructor Java Method
• Constructor is used to initialize the state of an object. • Method is used to expose behavior of an object.
• Constructor must not have return type. • Method must have return type.
• Constructor is invoked implicitly. • Method is invoked explicitly.
• Constructor name must be the same as the class name. • Method is not provided by compiler in any case.
• The java compiler provides a default constructor if none • Method name may or may not be same as class name.
is present.

Understanding static
Static method/instance variable: Can be accessed before any objects of its class are created, and without reference to any

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 16


object
• main( ) is declared as static because it must be called before any objects exist
• Static instance variables are essentially global variables because all instances of the class share the same static variable
• Methods declared as static have several restrictions:
1. "Can only directly call other static methods": Static methods can only invoke other static methods within the same class
directly. They cannot call non-static (instance) methods without first creating an instance of the class.
2. "Can only directly access static data": Static methods can directly access static variables (class variables) within the same
class. However, they cannot directly access instance variables (non-static variables) without an object reference.
3. "Cannot refer to this or super in any way": Within a static method, the keywords `this` and `super` are not allowed to
refer to the current instance or the superclass, respectively. This is because static methods belong to the class itself, rather than
any specific instance of the class. Therefore, there is no concept of a current instance (`this`) in the context of a static method.
Accessing static members : static methods and variables can be used independently of any object; specify the name of their
class followed by the dot operator

In summary, static methods are associated with the class rather than individual instances, and they have limited access to other
class members compared to instance methods. They cannot manipulate instance variables directly or reference the current instance
using `this`, as they are not associated with any particular object's state.Initializing static variables : declare a static block that gets
executed exactly once, when the class is first loaded
Example:
public class Counter {
private static int count = 0; // static instance variable
public Counter() {
count++; // Increment count each time a new Counter object is created
}
public static int getCount() { // static method to access count
return count;
}
public static void resetCount() { // static method to reset count to zero
count = 0;
}
}

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println("Number of Counter objects created: " + Counter.getCount());
Counter.resetCount(); // Reset the count to zero
System.out.println("Number of Counter objects after reset: " + Counter.getCount());
}
}
Output: Number of Counter objects created: 3
Number of Counter objects after reset: 0
This code consists of two classes: `Counter` and `Main`. Let's explain each part:

1. `Counter` class:
- This class represents a counter with a static instance variable `count`, which is initialized to 0.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 17


- The constructor `Counter()` increments the `count` variable each time a new `Counter` object is created.
- The static method `getCount()` allows external code to access the current value of the `count` variable.
- The static method `resetCount()` resets the `count` variable to zero.
2. `Main` class:
- This class contains the `main` method, which serves as the entry point of the program.
- Inside the `main` method, three `Counter` objects (`c1`, `c2`, and `c3`) are created.
- Each time a `Counter` object is created, the `count` variable in the `Counter` class is incremented.
- After creating the `Counter` objects, it prints the total number of `Counter` objects created using the `getCount()` method.
- Next, the `resetCount()` method is called to reset the `count` variable to zero.
- Finally, the program prints the total number of `Counter` objects again, confirming that the count has been reset.

Introducing final
The `final` keyword in Java is used to apply restrictions on classes, methods, and variables. When applied to a class, it indicates that
the class cannot be subclassed. When applied to a method, it indicates that the method cannot be overridden by subclasses. When
applied to a variable, it indicates that the variable's value cannot be changed once initialized. Let's provide examples for each case:
1. Final Class:
final class FinalClass {
// Class implementation
}
In this example, `FinalClass` is declared as `final`, meaning it cannot be subclassed. Any attempt to extend this class will result
in a compilation error.
2. Final Method:
class ParentClass {
final void finalMethod() {
// Method implementation
}
}
class ChildClass extends ParentClass {
// Attempting to override finalMethod will result in a compilation error
}
In this example, the `finalMethod()` in `ParentClass` is declared as `final`, indicating that it cannot be overridden by
subclasses. Any attempt to override this method in a subclass will result in a compilation error.
3. Final Variable:
class MyClass {
final int constantValue = 10;

void modifyConstant() {
// Attempting to modify constantValue will result in a compilation error
// constantValue = 20;
}
}
In this example, `constantValue` is declared as `final`, meaning its value cannot be changed once initialized. Any attempt to
modify the value of `constantValue` after initialization will result in a compilation error.
These examples demonstrate how the `final` keyword can be used to enforce immutability and restrict inheritance and method
overriding in Java.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 18


The ‘this’ keyword in java
Usage of java this keyword: Here is given the 5 usage of java this keyword.
What is the significance of “this” keyword in java
In Java, "this" is a keyword that refers to the current instance of the class. It is commonly used within the class to refer to the
instance variables and methods of that class. The "this" keyword is especially useful when there is a need to disambiguate
between instance variables and parameters with the same name within a method or constructor.
1. Accessing Instance Variables: Inside an instance method or constructor, you can use "this" to refer to the current
instance of the class. This is often used to access or modify instance variables of the class.
public class MyClass {
private int value;
public void setValue(int value) {
this.value = value; // "this" refers to the current instance of MyClass
}
}

2. Avoiding Name Conflicts: When a method or constructor parameter has the same name as an instance variable, the
"this" keyword can be used to distinguish between them.
public class MyClass {
private int value;
public void setValue(int value) {
this.value = value; // "this.value" refers to the instance variable, and "value" refers to the
parameter
}
}

3. Passing the Current Object: Sometimes, you might need to pass the current object as an argument to other methods
or constructors. The "this" keyword is used for this purpose.
public class MyClass {
private int value;
public MyClass() {
initialize(this); // Passing the current object as an argument
}
private void initialize(MyClass obj) {
// Do something with the obj parameter
obj.setValue(42); // Setting the value of the passed object to 42
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public static void main(String[] args) {
MyClass myObject = new MyClass();
System.out.println("Value of myObject: " + myObject.getValue());
}
}

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 19


4. Chain Constructors: In Java, constructors can call other constructors using the "this" keyword to avoid code
duplication and initialize common fields.
public class MyClass {
private int value;
public MyClass() {
this(0); // Call another constructor of the same class
}
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public static void main(String[] args) {
MyClass myObject1 = new MyClass(); // Calls the default constructor
System.out.println("Value of myObject1: " + myObject1.getValue());
MyClass myObject2 = new MyClass(42); // Calls the parameterized constructor
System.out.println("Value of myObject2: " + myObject2.getValue());
}
}

5. Static Context: The "this" keyword cannot be used within a static method, as static methods belong to the class and not
to any specific instance.
public class MyClass {
private static int staticValue;
public static void setStaticValue(int value) {
staticValue = value; // Correct way to access static variables
}
public static int getStaticValue() {
return staticValue;
}
public static void main(String[] args) {
MyClass.setStaticValue(42); // Setting the static value to 42
System.out.println("Static Value: " + MyClass.getStaticValue()); // Retrieving the static value
}
}

In summary, the "this" keyword in Java is used to refer to the current instance of the class. It is most commonly used to
access instance variables, avoid name conflicts, pass the current object to other methods or constructors, and chain
constructors within a class. However, it cannot be used within static methods as static methods do not have access to any
specific instance of the class.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 20


Arrays Revisited
Arrays were introduced earlier in this book, before classes had been discussed. Now that you know about classes, an important
point can be made about arrays: they are implemented as objects. Because of this, there is a special array attribute that you will want
to take advantage of. Specifically, the size of an array—that is, the number of elements that an array can hold—is found in its length
instance variable. All arrays have this variable, and it will always hold the size of the array. Here is a program that demonstrates
this property.
Here's an example program that demonstrates the use of the `length` instance variable of arrays:
public class Main {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = { 10, 20, 30, 40, 50 };
// Print the length of the array
System.out.println("Length of the array: " + numbers.length);
// Access elements of the array using a loop
System.out.println("Elements of the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// Create another array with a different length
String[] names = new String[3];
// Print the length of the new array
System.out.println("Length of the new array: " + names.length);
}
}
Explanation:
- We declare and initialize an array `numbers` containing five integer elements.
- We access the length of the array using the `length` instance variable and store it in the variable `length`.
- We print the length of the array using `System.out.println`.
- We iterate over each element of the array using a `for` loop and print each element along with its index.
- The output will display the length of the array and each element along with its index.
This program illustrates the use of the `length` instance variable to determine the size of an array and how to iterate over the
elements of the array using its length.

A Stack Class : Write class called Stack that implements a stack for integers:
In this implementation, the Stack class has an integer array data to store the elements, a variable top to keep track of the top
index of the stack, and capacity to set the maximum size of the stack. The class provides methods like push, pop, peek,
isEmpty, and isFull to manipulate and query the stack.
The main method demonstrates how to use the Stack class by pushing and popping elements from the stack. The output
shows the popped value, peeked value, and the size of the stack after some operations.
public class Stack {
private int[] data;
private int top;
private int capacity;
public Stack(int capacity) {
this.data = new int[capacity];
this.top = -1;
this.capacity = capacity;
}

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 21


public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1;
}
public void push(int value) {
if (isFull()) {
System.out.println("Stack is full. Cannot push " + value);
return;
}
data[++top] = value;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop.");
return -1; // Alternatively, you can throw an exception to indicate the error.
}
return data[top--];
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Alternatively, you can throw an exception to indicate the error.
}
return data[top];
}
public int size() {
return top + 1;
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Popped value: " + stack.pop()); // Output: Popped value: 3
System.out.println("Peeked value: " + stack.peek()); // Output: Peeked value: 2
System.out.println("Stack size: " + stack.size()); // Output: Stack size: 2
} }

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 22


Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties Syntax
and behavior of a parent object. The idea behind inheritance in Java is that you can class Super {
create new classes that are built upon existing classes. When you inherit from an .....
existing class, you can reuse methods and fields of the parent class. .....
extends Keyword: extends is the keyword used to inherit the properties of a class. }
Following is the syntax of extends keyword. class Sub extends Super{
Example: .....
class Calculation { .....
int z; }
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:" + z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:" + z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:" + z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 23


Member Access and Inheritance:
Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private. For example, consider the following simple class hierarchy:
class Superclass {
private int privateField;
public Superclass(int privateField) {
this.privateField = privateField;
}
public void display() {
System.out.println("Private field value: " + privateField);
}
}
class Subclass extends Superclass {
public Subclass(int privateField) {
super(privateField);
}
}
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass(10);
// Attempting to access privateField from subclass will result in a compilation error
// System.out.println(obj.privateField);
obj.display(); // This will work as display method is inherited from superclass
}
}
In this example: We have a superclass `Superclass` with a private field `privateField`. The `display()` method in `Superclass`
prints the value of `privateField`. We have a subclass `Subclass` which extends `Superclass`. In the `Subclass` constructor, we
call the superclass constructor to initialize `privateField`. In the `Main` class, we create an object of `Subclass`. If we try to
access `privateField` directly from the `Subclass` object, it will result in a compilation error because `privateField` is not
accessible outside of the `Superclass`. However, we can still access and use the `display()` method inherited from the
`Superclass`.
** This demonstrates that A class member that has been declared as private will remain private to its class It is not
accessible by any code outside its class, including subclasses

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 24


A Superclass Variable Reference to a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. You will find
this aspect of inheritance quite useful in a variety of situations.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
public void fetch() {
System.out.println("Dog fetches a stick");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Superclass reference variable referencing a Subclass object
// Call methods using the Animal reference
animal.sound(); // This will invoke the overridden sound method in Dog class
animal.fetch(); // This will result in error because Animal class does not have a fetch method
// However, we can still call fetch method by casting the reference to Dog type
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.fetch(); // This will work fine as animal is referencing a Dog object
}
}
}

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 25


Using super to call Superclass Constructors
In Java, the `super` keyword is used to refer to the superclass (parent class) of the current class. It can be used to call the
superclass constructor, superclass methods, or access superclass variables. When calling a superclass constructor using
`super`, it must be the first statement in the subclass constructor. This is useful when the subclass constructor needs to
initialize inherited fields or perform common initialization tasks defined in the superclass constructor.
Here's an example demonstrating the use of `super` to call superclass constructors:
class Animal {
protected String species; // Protected superclass variable
public Animal(String species) {
this.species = species;
}
public void displaySpecies() {
System.out.println("Species: " + species);
}
}

class Dog extends Animal {


private String breed;
public Dog(String species, String breed) {
super(species); // Call superclass constructor
this.breed = breed;
}
public void displayDetails() {
super.displaySpecies(); // Call superclass method
System.out.println("Breed: " + breed);
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Canine", "Labrador");
dog.displayDetails();
}
}

output:
Species: Canine
Breed: Labrador
The Animal class has a species variable and a displaySpecies() method to print the species.
The Dog class extends Animal and adds a breed variable.
In the Dog constructor, super(species) is used to call the superclass constructor and initialize the species variable.
The displayDetails() method in Dog calls the displaySpecies() method of the superclass using super.displaySpecies() to print the species.
In the Main class, we create a Dog object and invoke its displayDetails() method.

This demonstrates how super can be used to call superclass constructors, to access superclass methods (displaySpecies())
and variables (species), allowing subclasses to utilize and extend functionality provided by the superclass.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 26


Using super to access Superclass hidden members
Hidden variables in Java occur when a subclass declares a variable with the same name as a variable in its superclass. This
hides the superclass variable within the subclass, meaning that references to that variable within the subclass will refer to the
subclass variable, not the superclass variable.
Here's an example illustrating hidden variables:
class Animal {
protected String species = "Animal"; // Superclass variable
public void displaySpecies() {
System.out.println("Species: " + species);
}
}
class Dog extends Animal {
private String species = "Canine"; // Hidden variable
public void displaySpecies() {
System.out.println("Species: " + species); // Refers to the subclass variable
System.out.println("Superclass species: " + super.species); // Refers to the superclass variable
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.displaySpecies();
}
}
output:
Species: Canine
Superclass species: Animal
Explanation:
- The `Animal` class has a `species` variable with the value `"Animal"`.
- The `Dog` class extends `Animal` and declares a `species` variable with the value `"Canine"`. This variable hides the `species` variable from
the superclass.
- The `displaySpecies()` method in `Dog` prints the value of the subclass `species` variable using `this.species`, and then it prints the value of
the superclass `species` variable using `super.species`.

This demonstrates how hidden variables in a subclass can be accessed and how the superclass variable can be accessed using
`super`.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 27


Multilevel Inheritance
Multilevel inheritance is a type of inheritance in object-oriented programming where a class inherits properties and
behaviors from another class, which in turn inherits from another class, forming a chain of inheritance. In multilevel
inheritance, each subclass serves as a superclass for another subclass, creating multiple levels or tiers of inheritance.
Here's a simple example to illustrate multilevel inheritance:
// Superclass
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
}
// Subclass inheriting from Dog
class Bulldog extends Dog {
public void guard() {
System.out.println("Bulldog is guarding");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Bulldog bulldog = new Bulldog();
bulldog.eat(); // Inherited from Animal
bulldog.bark(); // Inherited from Dog
bulldog.guard(); // Specific to Bulldog
}
}

Explanation:
- We have a superclass `Animal` with a method `eat()`.
- `Dog` class is a subclass of `Animal` and inherits the `eat()` method. It also has its own method `bark()`.
- `Bulldog` class is a subclass of `Dog` and inherits both `eat()` and `bark()` methods. It also adds its own method `guard()`.
- In the `Main` class, we create an object of `Bulldog` class and demonstrate how methods are inherited through multiple levels of inheritance.

Multilevel inheritance allows for the reuse of code and promotes code organization by organizing classes into a hierarchy
based on their relationships. However, it can also lead to tight coupling and complexity if not used carefully.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 28


Method Overriding
Method overriding is a concept in object-oriented programming where a subclass provides a specific implementation of a
method that is already defined in its superclass. This allows the subclass to provide its own behavior for the method, which
may differ from the behavior defined in the superclass. Method overriding is a feature of inheritance and allows for
polymorphic behavior, where the method to be invoked is determined at runtime based on the actual type of the object.
Here's an example to illustrate method overriding:
// Superclass
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass overriding makeSound() method
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
// Subclass overriding makeSound() method
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Animal dog = new Dog(); // Dog object, Animal reference
Animal cat = new Cat(); // Cat object, Animal reference

dog.makeSound(); // Calls Dog's makeSound() method


cat.makeSound(); // Calls Cat's makeSound() method
}
}
Output:
Dog barks
Cat meows
Explanation:
- We have a superclass `Animal` with a method `makeSound()`.
- `Dog` and `Cat` classes are subclasses of `Animal` and override the `makeSound()` method with their specific implementations.
- In the `Main` class, we create objects of `Dog` and `Cat`, but we use references of type `Animal` to store them.
- When calling the `makeSound()` method on these objects, the overridden version of the method is invoked based on the actual type of the
object, demonstrating polymorphic behavior.
This example demonstrates how method overriding allows subclasses to provide their own implementation of a method
inherited from a superclass, enabling different behavior for objects of different subclasses while adhering to a common
interface defined by the superclass.

Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy