Unit 2
Unit 2
Constructors
• A constructor is a special method used to initialize objects. It has the same
name as the class and no return type.
Default Constructor:
• Automatically provided by Java if no
• constructor is explicitly defined.
class Student
{ int id; public class Main {
String public static void main(String[] args) {
name; Student s = new Student();
Student() { s.display();
id = 0; }
name = "Unknown"; }
}
void display() {
System.out.println("ID: " + id + ", Name: " + name);
}
} PIMPRI CHINCHWAD UNIVERSITY
9
Default Constructor:
class DefaultConstructorExample {
int x;
DefaultConstructorExample() {
x = 10; // Assign default value
System.out.println("Default constructor called. Value of x: " + x);
}
Parameterized Constructor:
• Used to initialize fields with specific
`
values.
• class Student {
public class Main {
int id; public static void main(String[] args)
String name; { Student s = new Student(101, "John"); s.display();
Student(int id, String name) }
}
{ this.id = id;
this.name = name;
}
void display() {
System.out.println("ID: " + id + ", Name: " +
name);
} PIMPRI CHINCHWAD UNIVERSITY
12
Parameterized Constructor:
class ParameterizedConstructorExample {
int x;
ParameterizedConstructorExample(int value) {
x = value;
System.out.println("Parameterized constructor called. Value of x: " + x);
}
Copy Constructor:
class CopyStudent {
int x;
CopyStudent(int value) {
x = value;
}
CopyStudent(CopyStudent obj) {
x = obj.x;
System.out.println("Copy constructor called. Value of x: " + x);
}
Constructor Overloading:
• Allows multiple constructors with different parameter lists.
void display() {
class Student {
System.out.println("ID: " + id + ", Name: " + name);
int id;
}
String name;
}
Student() {
public class Main {
id = 0;
public static void main(String[] args) {
name = "Unknown";
Student s1 = new Student();
}
s1.display();
Student(int id, String name) {
Student s2 = new Student(102, "Alice");
this.id = id;
s2.display();
this.name = name;
}
}
}
PIMPRI CHINCHWAD UNIVERSITY
14
Constructor Overloading:
class ConstructorOverloadingExample {
int x;
ConstructorOverloadingExample() {
x = 10;
}
ConstructorOverloadingExample(int value) {
x = value;
}
public static void main(String[] args) {
ConstructorOverloadingExample obj1 = new ConstructorOverloadingExample();
ConstructorOverloadingExample obj2 = new ConstructorOverloadingExample(40);
class StaticBlockVsConstructor {
static {
System.out.println("Static block called.");
}
StaticBlockVsConstructor() {
System.out.println("Constructor called.");
}
Methods
• Methods define the behavior of a class. They can accept parameters and return
values.
ObjectCounter() {
count++;
}
ObjectCounter.displayCount();
}
19
Counter() {
count++;
}
//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();
}
}
Can a class in Java be declared as private or protected?
this Reference
• The “this” keyword in Java refers to the current object of a class. It is primarily
used to resolve conflicts between instance variables and parameters when their
names are the same.
Recursion
• Recursion is a technique in which a method calls itself to solve a smaller instance
of the same problem.
Recursion - Example
class Factorial {
int calculateFactorial(int n) {
if (n == 1) return 1; // Base case
return n * calculateFactorial(n - 1);
}
}
boolean equalsIgnoreCase(String another) Checks if two strings are equal, ignoring case considerations.
String concat(String str) Concatenates the specified string to the end of the current string.
boolean contains(CharSequence s) Checks if the string contains the specified sequence of characters.
boolean startsWith(String prefix) Checks if the string starts with the specified prefix.
boolean endsWith(String suffix) Checks if the string ends with the specified suffix.
int indexOf(String str) Returns the index of the first occurrence of the specified substring.
int lastIndexOf(String str) Returns the index of the last occurrence of the specified substring.
String substring(int beginIndex) Returns a new string starting from the specified index.
String substring(int beginIndex, int endIndex) Returns a substring from the start index to the end index (exclusive).
String replace(char oldChar, char newChar) Replaces all occurrences of a character with another character.
String[] split(String regex) Splits the string around matches of the given regular expression.
static String valueOf(Object obj) Returns the string representation of the specified object.
boolean matches(String regex) Checks if the string matches the given regular expression.
Garbage Collection
• Garbage Collection (GC) in Java is an automated process that manages
memory by reclaiming memory occupied by objects that are no longer in
use.
• It helps prevent memory leaks and ensures efficient memory utilization.
Garbage Collection
class Demo {
protected void finalize() throws Throwable {
System.out.println("Object is garbage collected");
}
}
The finalize() method is called by the garbage collector before the object is destroyed. The System.gc()
method is a request to initiate garbage collection, though its execution depends on the JVM.
Inheritance
• Inheritance allows a class to acquire properties and behaviors from another class,
promoting code reuse and organization.
• Types of Inheritance:
1. Single Inheritance: A class inherits from one parent class.
2. Multilevel Inheritance: A class inherits from a parent class, which is
itself a child of another class.
3. Hierarchical Inheritance: Multiple classes inherit from a single parent
class.
Inheritance
class Parent {
void displayParent() {
System.out.println("This is the parent class.");
}
}
void displayMessages() {
System.out.println(message);
System.out.println(super.message);
}
}
Polymorphism
• Polymorphism in Java is the ability of an object to take many forms. It allows
methods to perform different tasks based on the object that calls them, enhancing
code flexibility and reusability.
Polymorphism
• Types of Polymorphism
• Polymorphism in Java can be broadly categorized into:
1. Compile-Time Polymorphism (Static Polymorphism)
2. Run-Time Polymorphism (Dynamic Polymorphism)
Polymorphism
• Compile-Time Polymorphism (Static Polymorphism)
Explanation:Compile-time polymorphism is achieved through method
overloading. The method to be invoked is determined at compile-time
based on the method signature.
• Method Overloading
• Method overloading occurs when multiple methods in the same class
share the same name but differ in:
1. Number of parameters
2. Type of parameters
3. Sequence of parameters
Polymorphism
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
Polymorphism
public class MethodOverloadingExample {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of 2 integers: " + calc.add(10, 20));
System.out.println("Sum of 3 integers: " + calc.add(10, 20, 30));
System.out.println("Sum of 2 doubles: " + calc.add(10.5, 20.5));
}
}
Polymorphism
• Run-Time Polymorphism (Dynamic Polymorphism)
Explanation:Run-time polymorphism is achieved through method
overriding. The method to be invoked is determined at run time based
on the object's actual type.
• Method Overriding
• Method overriding occurs when a subclass provides a specific
implementation of a method already defined in its superclass.
• The overriding method must have:
1. The same method name
2. The same return type
3. The same parameter list
Polymorphism
class Animal {
void sound() {
System.out.println("This is a generic animal sound.");
}
public class MethodOverridingExample {
}
public static void main(String[] args) {
Animal animal;
class Dog extends Animal {
@Override
animal = new Dog(); // Dog-specific sound
void sound() {
animal.sound();
System.out.println("The dog barks.");
}
} animal = new Cat(); // Cat-specific sound
animal.sound();
}
class Cat extends Animal {
}
@Override
void sound() {
System.out.println("The cat meows.");
}
} PIMPRI CHINCHWAD UNIVERSITY
47
Preventing Inheritance:
• Using the final keyword prevents inheritance of classes or overriding of methods.
Preventing Inheritance:
final class FinalClass {
}
//}
class Parent {
final void display() {
System.out.println("Final method");
}
}
Final Variables
public class FinalVariableExample {
final int CONSTANT = 100; // Final variable
void display() {
// CONSTANT = 200; //
System.out.println("CONSTANT: " + CONSTANT);
}
Final Methods
class Parent {
final void display() {
System.out.println("Final method in Parent class");
}
}
class Child extends Parent {
// void display() { }
}
Final Classes
final class FinalClass {
void display() {
System.out.println("This is a final class");
}
}
class Child extends FinalClass { } //
void makeSound() {
System.out.println("Bark!");
}
}
Assignment Questions
1. Student Management System: Create a Student class with fields like id, name, and
marks. Add methods to display details and calculate grades based on marks. Write
a program to create multiple student objects and display their details and grades.
2. Bank Account Simulation: Create a BankAccount class with fields accountNumber,
accountHolderName, and balance. Implement methods for deposit, withdrawal,
and displaying account details. Ensure balance does not go negative.
3. Default Constructor for Book Details: Create a Book class with fields title, author,
and price. Use a default constructor to initialize default values and display them.
Assignment Questions
4. Parameterized Constructor for Employee Details: Create an Employee class with
fields id, name, and salary. Use a parameterized constructor to initialize the fields
and display the employee details.
5. Constructor Overloading for Shapes: Create a Shape class with overloaded
constructors:
a. Default constructor initializes a circle with a default radius.
b. A constructor with parameters initializes a rectangle with length and
breadth.
c. Write a program to calculate the area based on the constructor invoked.
Assignment Questions
6. Track Object Count: Create a Product class with a static field productCount to track
the number of objects created. Use a static method to display the total count.
7. Temperature Converter: Create a Temperature class with a static method to
convert temperature between Celsius and Fahrenheit. Write a program to
demonstrate its usage.
8. Access Control in Employee Details: Create an Employee class with fields id
(private), name (protected), and department (public). Use appropriate access
modifiers and demonstrate access in another class within the same package and a
subclass.
PIMPRI CHINCHWAD UNIVERSITY
51
Assignment Questions
9. Using this to Resolve Conflicts: Create a Car class with fields brand, model, and price. Use
the this keyword in the constructor to differentiate between instance variables and
parameters with the same name.
10. Fibonacci Series: Write a program to calculate the nth Fibonacci number using recursion.
11. Sum of Digits: Write a recursive program to calculate the sum of digits of a given number.
12. Text Analysis: Write a program to process a paragraph of text and perform the following
operations:
1. Count the number of words.
2. Find and replace a specific word.
3. Extract the first sentence.
4. Convert the text to uppercase and lowercase.
PIMPRI CHINCHWAD UNIVERSITY
52
Assignment Questions
13. Palindrome Check: Write a program to check if a given string is a palindrome.
Ignore case and spaces.
14. Object Cleanup: Create a Resource class with a finalize() method to display a
message when an object is garbage collected. Write a program to demonstrate
garbage collection.
15. Vehicle Inheritance: Create a base class Vehicle with a method move(). Create
subclasses Car and Bike that override the move() method with specific
implementations. Demonstrate runtime polymorphism by calling the move()