Java Notes Arrays and Etc
Java Notes Arrays and Etc
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.
Brief Recap:
Decision-making statements in Java, including if statements and switch statements, enable programmers
to control the flow of execution based on specific conditions. If statements evaluate Boolean expressions
and execute corresponding blocks of code if the conditions are met. They can be extended with else if and
else clauses for more complex decision-making.
Switch statements, on the other hand, allow a variable to be tested for equality against multiple values.
Each value is associated with a case, and the corresponding block of code executes if the variable
matches that value. Fall-through behavior can occur if break statements are omitted between cases.
In practice, if-else-if statements are often used for simpler conditional checks, while switch statements
are preferred for handling multiple possible values of a variable. However, the choice between them
depends on the specific requirements of the program and readability considerations.
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()`).
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.
Explanation:
By providing both constructors, you can initialize objects either with default values or with custom values based on your
requirements.
Brief Recap:
Java, a class serves as a blueprint or template for creating objects. It defines the structure and behavior
of objects through data members (fields) and methods (functions). Objects are instances of classes,
created using the new keyword followed by the class name.
The process of object creation involves declaration, instantiation, and initialization. Declaration involves
declaring a variable of the class type, instantiation allocates memory for the object using the new
keyword, and initialization sets initial values for the object's attributes.
Constructors are special methods used for initializing objects. Default constructors are automatically
provided by Java if no constructors are defined explicitly, while parameterized constructors take
arguments to initialize object attributes with custom values.
The new keyword is crucial in object creation, dynamically allocating memory for objects at runtime. It
is also used for creating arrays in Java. Understanding object creation and initialization is fundamental
to working with classes and objects in Java programming.
// 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());
// Initializing using the parameterized constructor
Box paramBox = new Box(5.0, 3.0, 2.0);
1. What happens when you assign an object reference variable to another reference variable in Java?
2. Explain the concept of object reference variables and their behavior during assignment.
3. Why does the assignment Box b2 = b1; not create a new object in memory?
4. What is the significance of understanding object reference behavior in Java?
1. How can you create an array object in Java using the new keyword
2. What are parameterized methods? How do they differ from non-parameterized methods? Provide an
example of each type of method in Java.
3. Explain with an example what happens When you assign an object reference variable to another
reference variable in Java?
4. Give a Java Coe to Creating an Array Object
5. Differentiate between Parameterized Methods vs. Non-Parameterized Methods
Brief Recap:
Creating Objects and assignment to Reference Variables: No memory allocation or copying occurs
during this assignment. Changes made through b2 will affect the object referred to by b1.
Parameterized Methods vs. Non-Parameterized Methods : Parameterized methods accept input
parameters when called, allowing dynamic behavior based on provided data. Non-parameterized
methods perform fixed operations without external input.
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
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) {
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.
Brief Recap:
Use of this keyword in Accessing Instance Variables
Use of this keyword in Avoiding Name Conflicts
Use of this keyword in Passing the Current Object
Use of this keyword in Chain Constructors
Use of this keyword in Static Context
The “this” keyword in Java is a powerful tool for working with instance variables, avoiding conflicts,
passing objects, and chaining constructors. However, remember that it cannot be used within static
methods since they don’t have access to any specific instance
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;
}
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.
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) {
Session 17: 11-06-24 Using Objects as Parameters, A Closer Look at Argument Passing.
Brief Recap:
Method Overloading:
When multiple methods in the same class share the same name but have different parameter declarations
(type and/or number).
Java determines which version of the overloaded method to call based on argument types or count.
Return type alone is insufficient to distinguish between method versions.
Automatic type conversions can play a role in overload resolution.
Constructors can also be overloaded.
Stack Class:
The Stack class uses an integer array called data to store elements.
It maintains a top variable to track the index of the top element in the stack.
The capacity field sets the maximum size of the stack.
Methods include push, pop, peek, isEmpty, and isFull.
The main method demonstrates usage by pushing, popping, and displaying stack size.
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`.
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);
Brief Recap:
In Java, you can pass objects as parameters to methods, similar to how you pass primitive data types.
When you pass an object as a parameter, you’re essentially passing a reference to that object. This allows
the method to access and modify the object’s properties.
Rectangle Class:
Represents a rectangle with width and height.
Contains a constructor to initialize width and height and a method area() to calculate the area of the
rectangle.
Main Class:
Defines a static method doubleArea(Rectangle r) that takes a Rectangle object as a parameter.
Inside doubleArea(), the width and height of the rectangle passed as a parameter are doubled.
In the main() method, we create a Rectangle object named rect with width 5 and height 3.
We call doubleArea(rect) and print the area of the rectangle to see the effect of doubling the width and
height.
Remember that when you pass an object as a parameter, any changes made to the object within the
method affect the original object outside the method.
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
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.
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
Brief Recap:
The provided Rectangle class models rectangles with length and width attributes. The calculateArea()
method computes the area based on these dimensions.
The createRectangle() method returns a new Rectangle object initialized with specified dimensions.
Recursion is a powerful technique for solving problems by breaking them down into smaller sub-
problems. The factorial() method exemplifies recursion in Java.
The displayArray() method (incomplete in the provided code) recursively displays elements of an array.
Understanding static
Static method/instance-variable: Can be accessed before any objects of its class are created, and without reference to any
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
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
}
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
Brief Recap:
Static is a keyword used for memory management mainly. It signifies single-copy storage for
variables or methods.
Members marked with the static keyword inside a class are called static members.
♦ Here are some key points about static:
♦ Static Methods and Instance Variables:
♦ Static methods and instance variables can be accessed before any objects of their class are created
and without reference to any object.
Restrictions on Static Methods:
Static methods have several restrictions:
They can only directly call other static methods within the same class. Non-static (instance) methods
cannot be called directly without first creating an instance of the class.
They 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.
Within a static method, the keywords this and super are not allowed to refer to the current instance or the
superclass, respectively.
Accessing Static Members:
Static methods and variables can be used independently of any object. You specify the name of their
class followed by the dot operator.
Initializing Static Variables:
Declare a static block that gets executed exactly once when the class is first loaded.
Arrays Revisited
Arrays were introduced earlier , 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
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties
and behavior of a parent object. The idea behind inheritance in Java is that you can Syntax
create new classes that are built upon existing classes. When you inherit from an class Super {
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. }
Example: class Sub extends Super{
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
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.
Brief Recap:
Arrays are fundamental data structures in programming.
All arrays have a special attribute called length.
The length instance variable always holds the size (number of elements) of the array.
You can access the length of an array using arrayName.length.
Inheritance in Java allows one object to acquire all the properties and behavior of a parent object.
Inheritance is a mechanism where one class (subclass or derived class) acquires the properties and
behavior of another class (superclass or base class).
It allows you to create new classes based on existing classes, promoting code reuse.
extends Keyword: The extends keyword is used to inherit the properties of a class. Syntax: class Subclass
extends Superclass { ... }
Types of Inheritance:
Single inheritance (one superclass)
Hierarchical inheritance (one superclass, many subclasses)
Multilevel inheritance (derived from a derived class)
Multiple inheritance (several superclasses)
Hybrid inheritance (more than one superclass and subclass)
**Note: Java directly supports single inheritance but implements multiple inheritance using interfaces.
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.
In the given example:
We have an Animal class with a sound() method that prints “Animal makes a sound.”
The Dog class extends Animal and overrides the sound() method to print “Dog barks.”
In the Main class:
We create an Animal reference variable (animal) and assign it a Dog object (new Dog()).
We call the sound() method using the animal reference, which invokes the overridden method in the Dog
class (output: “Dog barks”).
Attempting to call the fetch() method (which is specific to Dog) using the animal reference results in an
error because the Animal class does not have a fetch() method.
We can still call the fetch() method by casting the reference to Dog type.
Using super to Call Superclass Constructors:
• The super keyword is used to refer to the superclass of the current class.
• It can be used to call the superclass constructor.
• In the given example:
The Animal class has a protected species variable and a constructor that initializes it.
The Dog class extends Animal and adds a private breed variable.
In the Dog constructor, we use super(species) 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() (output: “Species: Canine”).
We create a Dog object with species “Canine” and breed “Labrador” and invoke its displayDetails() method.
Using super to Access Superclass Hidden Members:
Programming in Java: 21CS652 Dr. Ganesh V Bhat, Department 0f ECE @ CEC 36
• Hidden variables occur when a subclass declares a variable with the same name as a variable in its
superclass.
example: The Animal class has a species variable set to “Animal.”
The Dog class declares a private species variable set to “Canine,” hiding the superclass variable.
When calling displaySpecies() in Dog, it refers to the subclass variable (output: “Species: Canine”).
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.
Brief Recap:
Multilevel inheritance is a type of inheritance where a class inherits properties and behaviors from
another class, which in turn inherits from yet another class.Each subclass serves as a superclass for
another subclass, forming a chain of inheritance.
Method overriding allows a subclass to provide a specific implementation of a method already defined
in its superclass.
The subclass can override the behavior of the method, providing its own implementation.
It enables polymorphic behavior, where the method to be invoked is determined at runtime based on the
actual type of the object.