Java Notes Unit 2
Java Notes Unit 2
UNIT - 2
CLASSES AND OBJECTS
Introduction
Java is a true object-oriented language and therefore the underlying structure of all Java programs is
classes. Anything we wish to represent in a Java program must be encapsulated in a class that defines the
state and behavior of the basic program components known as objects. Classes create objects and objects
use methods to communicate between them.
In Java, the data items are called fields and the functions are called methods. How they are used to build
a Java program that incorporates the basic OOP concepts such as encapsulation, inheritance and
polymorphism.
Defining a Class:
A class is a user-defined datatype which has its own data members and member functions. In Java, the
data items are called fields and the functions are called methods. A class is a blue print with a template
that serves to define its properties.
A Class in Java can contain:
➢ Data member
➢ Method
➢ Constructor
➢ Nested Class
➢ Interface
Class declaration includes the following in the order as it appears:
Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
Example:
Adding Variables:
Data is encapsulated in a class by placing data fields inside the body of the class definition. These
variables are called instance variables because they are created whenever an object of the class is
instantiated.
Example:
class Rectangle
{
int length;
int width;
}
Methods Declaration:
A class with only data fields (and without methods that operate on that data) has no life. The objects
created by such a class cannot respond to any messages. We must therefore add methods that are necessary
for manipulating the data contained in the class. Methods are declared inside the body of the class but
immediately after the declaration of instance variables.
Syntax:
Class_name object_name = new Class_name( );
Accessing Objects:
All variables must be assigned values before they are used. To access class members outside the class,
the instance variables and the methods cannot be accessed directly. To use the concerned object and
the dot operator as shown below:
[Link];
[Link](Parameter-list);
void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
OUTPUT:
Name: Radha
Age: 20
Constructors
A constructor is a special method that is used to initialize an object.. A constructor does not have any
return type even void type.
A constructor has same name as the class in which it resides. Constructor in Java cannot be abstract,
static, final or synchronized. These modifiers are not allowed for constructor.
1. Default Constructor:
A default constructor is a constructor that does not take any parameters. It initializes the object with
default values.
Example:
class Student
{
String name;
int age;
// Default Constructor
Student()
{
name = "Mohan";
age = 20;
}
void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
OUTPUT:
Name:Mohan
Age: 20
2. Parameterized Constructor
A parameterized constructor is a constructor that accepts arguments. It is used to initialize data members
with user-defined values.
Example:
class Student
{
String name;
int age;
// Parameterized Constructor
Student(String n, int a)
{
name = n;
age = a;
}
void display()
{
3. Copy Constructor:
A copy constructor is a constructor that creates a new object by copying the values of another object of
the same class.
Student(String n, int a)
{
name = n;
age = a;
}
// Copy Constructor
Student(Student s)
{
name = [Link];
age = [Link];
}
void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
public class Main
{
public static void main(String[] args)
{
Student s1 = new Student("Radha ", 21);
Student s2 = new Student(s1);
[Link]();
}
}
OUTPUT:
Name: Radha
Age: 21
// Default Constructor
Student()
{
name = "Radha";
age = 18;
}
// Parameterized Constructor
Student(String n, int a)
{
name = n;
age = a;
}
// Copy Constructor
Student(Student s)
{
name = [Link];
age = [Link];
}
void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 9
OBJECT ORIENETED PROGRAMMING WITH JAVA
[Link]();
}
}
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Name: Radha
Age: 18
Name: Mohan
Age: 20
Name: Mohan
Age: 20
Constructor overloading
Constructor overloading means having multiple constructors in the same class with different parameter lists
(different number or type of arguments).
This allows objects to be created in multiple ways, providing flexibility for initialization depending on the
information available at the time of object creation.
Example:
class Student
{
String name;
int age;
void display()
{
[Link]("Name: " + name + ", Age: " + age);
}
}
public class ConstructorOverloading
{
public static void main(String[] args)
{
Student s1 = new Student(); // Uses default constructor
Student s2 = new Student("Amith"); // Uses constructor with 1 parameter
Student s3 = new Student("Bharath", 20); // Uses constructor with 2
parameters
OUTPUT:
Name: Unknown, Age: 0
Name: Amith, Age: 0
Name: Bharath, Age: 20
Method Overloading:
Method overloading in Java means defining multiple methods with the same name in a class, but with
different parameter lists (different number, type, or order of parameters).
This allows methods to perform similar tasks but with different types or numbers of inputs, improving
code readability and usability
EXAMPLE:
class Calculator
{
// Method with 2 int parameters
int add(int a, int b)
{
return a + b;
}
• Memory Management: Static members are stored in a special area of memory allocated to the
class, not to individual objects.
• Cannot Access Instance Data Directly: Static methods cannot directly access instance variables
or methods, as they do not belong to any specific object
Static Variable: A static variable is a variable that belongs to the class and is shared by all objects.
Static Method: A static method belongs to the class and can be called without creating an object.
class Employee
{
static String company = "TCS"; // Static variable
static void showCompany() // Static method
{
[Link]("Company: " + company);
}
}
Company: Infosys
Recursion:
Recursion is a programming technique where a method calls itself to solve a problem by breaking it
down into smaller, more manageable subproblems. This approach continues until it reaches a
condition known as the base case or halting condition, which stops the recursion
private Yes No No No No
1. Public
Members declared public are accessible from anywhere in the program, regardless of package
boundaries. This is the least restrictive access level.
Example:
public class Student
{
public String name; // Public variable
public void display() // Public method
{
[Link]("Student Name: " + name);
}
public static void main(String[] args)
{
Student s1 = new Student();
[Link] = "Rahul"; // Accessing public variable
[Link](); // Calling public method
}
}
OUTPUT: Student Name: Rahul
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 17
OBJECT ORIENETED PROGRAMMING WITH JAVA
2. private
Members declared private are accessible only within the class they are declared. This is the most
restrictive access level and is used to hide sensitive data or implementation details.
Example:
class Student
{
private String name; // Private variable
3. protected
Members declared protected are accessible within the same package and also in subclasses even if
they are in different packages. It provides a middle ground between public and default access.
Example:
class Student
{
protected String name; // Protected variable
}
}
OUTPUT:
Student Name: Rahul
4. default (package-private)
➢ When no access modifier is specified, the member is default (also called package-private).
Example:
class Student
{
String name; // Default access (no modifier)
this keyword
This keyword refers to the current object in a method or constructor. The most common use of the this
keyword is to eliminate the confusion between class attributes and parameters with the same name
(because a class attribute is shadowed by a method or constructor parameter).
Example:
class Student
{
String name;
int age;
// Constructor
Student(String name, int age)
{
[Link] = name; // '[Link]' refers to instance variable
[Link] = age; // '[Link]' refers to instance variable
}
void display()
{
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
public static void main(String[] args)
{
Student s1 = new Student("Rahul", 20);
[Link](); // Output: Name: Rahul, Age: 20
}
Definition:
The finalize() method is called by the garbage collector before an object is destroyed.
• It allows an object to perform cleanup operations (like closing files or releasing resources) before
memory is reclaimed.
• It is defined in the Object class.
Note: In modern Java versions, finalize() is deprecated because it is unpredictable
Key Points
1. Called automatically by garbage collector.
2. Used for cleanup operations before object is destroyed.
3. Should not be relied upon for critical cleanup because timing is uncertain.
4. Can be overridden in your class.
Example:
class Student
{
String name;
Student(String name)
{
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 22
OBJECT ORIENETED PROGRAMMING WITH JAVA
[Link] = name;
}
// finalize() is called before object is garbage collected
protected void finalize() {
[Link]([Link] + " is garbage collected.");
}
}
public class GarbageDemo
{
public static void main(String[] args)
{
Student s1 = new Student("Rahul");
Student s2 = new Student("Anita");
OUTPUT:
End of main method.
Rahul is garbage collected.
Anita is garbage collected.
INHERITANCE
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of
another. With the use of inheritance, the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class).
(OR)
The mechanism of deriving a new class from an old one is called inheritance. The old class is known as
the base class or super class or parent class and the new one is called the subclass or derived class or child
class.
Inheritance is implemented using the extends keyword.
Inheritance may take different forms:
1. Single inheritance (only one super class)
2. Multiple inheritances (several super classes)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multilevel inheritance (Derived from a derived class)
Why Use Inheritance?
• Code Reusability: Common code can be written once in a superclass and reused in multiple
subclasses.
• Extensibility: Subclasses can extend or enhance the functionality of a superclass.
• Polymorphism: Enables method overriding, allowing subclasses to provide
specific implementations for methods defined in the superclass.
• Hierarchical Organization: Helps manage and organize code in a logical, hierarchical manner
Basic Syntax:
class Superclass
{
// fields and methods
}
class Subclass extends Superclass
{
// additional fields and methods
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 24
OBJECT ORIENETED PROGRAMMING WITH JAVA
1. Single inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance.
Example:
class Animal
{
void eat()
{
[Link]("This animal eats food");
}
}
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived
class also acts as the base class for other classes. Or A class inherits from a class, which inherits from
another class (a chain).
Example:
class Animal
{
void eat()
{
[Link]("Eats food");
}
}
class Dog extends Animal
{
void bark() {
[Link]("Barks");
}
}
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Eats food
Barks
Weeps
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived classes B, C, and D.
Example:
class Animal
{
void eat()
{
[Link]("Eats food");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Barks");
}
}
class Cat extends Animal
{
void meow()
{
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 27
OBJECT ORIENETED PROGRAMMING WITH JAVA
[Link]("Meows");
}
}
public class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
[Link]();
[Link]();
}
// Interface for Cat
interface Cat
{
void meow();
}
// Class implementing both interfaces
class Pet implements Dog, Cat
{
public void bark()
{
[Link]("Dog barks: Woof Woof");
}
OVERRIDING METHODS:
Method overriding occurs when a subclass provides its own implementation of a method that is already
defined in its superclass.
• Same method name
• Same parameters (signature)
• Same return type (or compatible type)
It is used to change or extend the behavior of an inherited method.
// Subclass
class Cat extends Animal
{
@Override
void sound()
{
[Link]("Cat says: Meow Meow");
}
Example:
// Abstract class
abstract class Animal
{
abstract void sound(); // Abstract method
void sleep() // Concrete method
{
[Link]("Animal is sleeping");
}
// Subclass
class Dog extends Animal
{
@Override
void sound()
{
[Link]("Dog barks: Woof Woof");
}
}
Final Variables:
• A final variable is a constant, and its value cannot be modified after initialization.
• You must initialize a final variable when it's declared or in the constructor.
• If a final variable holds a reference to an object, the object's properties can still be modified,
but the variable itself will always refer to the same object.
Example:
class FinalVariableDemo
}
Final Methods:
• A final method cannot be overridden by subclasses.
• This ensures that the method's implementation remains consistent across all subclasses.
• Methods that should not be overridden, especially those in the constructor or related to
theobject's core state, are often made final.
Example:
class Animal
{
final void eat()
{
[Link]("Animal is eating");
}
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 35
OBJECT ORIENETED PROGRAMMING WITH JAVA
Example:
final class Calculator
{
int add(int a, int b)
{
return a + b;
}
}
ARRAYS
Java array is a collection of homogeneous data elements. It is an object which contains elements of a
similar data type. Additionally, the elements of an array are stored in a contiguous memory location. It is
a data structure where we store similar elements. Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored on 1st index and so on.
Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position. Arrays are used to store multiple
values in a single variable, instead of declaring separate variables for each value.
One-dimensional array:
A one-dimensional array can be visualized as a single row or a column of array elements that are
represented by a variable name and whose elements are accessed by index values.
one-dimensional array in java must deal with only one parameter. Entities of similar types can be stored
together using one-dimensional arrays. It can store primitive data types (int, float, char, etc.) or objects.
Declaration of one-dimensional array
data-type var-name[];
OR
data-type[] var-name;
OR
data-type []var-name;
[Link](a[i]);
}
}
}
Output:
10
20
70
40
50
Two-Dimensional Array
A 2D array is like a table made of rows and columns. It is a data structure used to store data in a grid-like
format with rows and columns.
You can think of it as a table or matrix, where:
• Each element is accessed using two indices – one for the row and one for the column.
• It is declared as: dataType[][] arrayName;
// Declaring 2D array
DataType[][] ArrayName;
// Creating a 2D array
ArrayName = new DataType[r][c];
Eg : //Declaring 2D array
int[][] a;
//Creating a 2D array
a = new int[3][3];
// Creating a 2D Array
DataType[][] ArrayName = new DataType[r][c]
// Accessing an element
DataType var = ArrayName[i][j];
Variable-size array:
. The most common alternative is ArrayList, you should use the ArrayList class from the [Link]
package.
Definition:
In Java, arrays have a fixed size once they are created —you can't change the size of an array after
initialization. However, you can simulate variable-sized arrays using other data structures
A variable-size array (also called dynamic array) is an array-like structure whose size can change during
runtime.
• In Java, normal arrays have fixed size, so we use ArrayList for variable-size arrays.
Example:
import [Link];
OUTPUT:
[Rahul, Anita]
STRINGS
String is a sequence of characters. In Java, string is an object that represents a sequence of characters. The
[Link] class is used to create a string object.
There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
By new keyword
String s=new String("Welcome");
//creates two objects and one reference variable
Example
public class StringExample
{
public static void main(String[] args)
{
// Creating a string
String name = "John";
// Printing the string
[Link]("Hello, " + name + "!");
// String length
[Link]("Length of name: " + [Link]());
}
}
Output
Hello, John!
Length of name: 4
Example program
public class StringHandlingExample
{
public static void main(String[] args)
{
String text = "Hello Java";
// 1. length()
[Link]("Length: " + [Link]());
// 2. toUpperCase()
[Link]("Uppercase: " + [Link]());
// 3. toLowerCase()
[Link]("Lowercase: " + [Link]());
// 4. charAt()
[Link]("Character at index 1: " + [Link](1));
// 5. substring()
[Link]("Substring (0 to 5): " + [Link](0, 5));
// 6. equals()
[Link]("Equals 'Hello Java': " + [Link]("Hello Java"));
// 7. contains()
[Link]("Contains 'Java': " + [Link]("Java"));
// 8. replace()
[Link]("Replace 'Java' with 'World': " + [Link]("Java", "World"));
}
}
Output
Length: 10
Uppercase: HELLO JAVA
Lowercase: hello java
Character at index 1: e
Substring (0 to 5): Hello
Equals 'Hello Java': true
Contains 'Java': true
Replace 'Java' with 'World': Hello World
StringBuffer Classes
StringBuffer in Java is a special class used to create and manage strings that can be changed or modified
after they are created. In contrast, regular String objects in Java cannot be changed once they are created
(they are immutable).
int a=20;
Integer b=[Link](a) ;//converting int into Integer explicitly
Integer c=a; //autoboxing, now compiler will write [Link](a) internally
[Link](a+" "+b+" "+c);
}
}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known asunboxing. It
is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper
classes to convert the wrapper type into primitives.
Wrapper Class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int b=[Link] Value();//converting Integer to int explicitly
int c=a;//unboxing, now compiler will write [Link]() internally
[Link](a+" "+b+" "+c);
}
}
Output:
333
INTERFACES IN JAVA
Interfaces: Multiple Inheritance
• An interface is a blueprint for classes.
• It can contain:
o Abstract methods (methods without body)
o Constants (variables are public static final by default)
• A class implements an interface and provides concrete implementations for all its methods.
• Supports multiple inheritance in Java (a class can implement multiple interfaces).
DEFINING INTERFACES:
An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a
major difference. The difference is that interfaces define only abstract methods and final fields.
This means that interfaces do not specify any code to implement these methods and data fields contain only
constants. The syntax for defining an interface is very similar to that for defining a class.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Here, interface is the keyword and interfacename is any valid Java variable(just like class names).
EXTENDING INTERFACES
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other
interfaces. The new subinterface will inherit all the members of the super interface in the manner similar
to subclasses. This is achieved using the keyword extends.
SYNTAX:
interface name2 extends name1
{
Body of name2
}
For example, we can put all the constants in one interface and the methods in the other. This will enable
us to use the constants in classes where the methods are not required. Example
interface ItemConstants
{
int code=1001 ;
String name=“Fan”;
}
interface Item extends ItemConstants
{
Void display();
}
Implementing Interface In Java
To implement an interface in Java, a class uses the implements keyword in its declaration, followed by a
comma-separated list of the interfaces it implements.
This establishes a contract where the class must provide implementations for all the methods defined in
the interface.
class classname implements interfacename
{
body of classname.
}
Here the class classname "implements" the interface interfacename. A more general form of
implementation may look like this:
{
body of classname
}
This shows that a class can extend another class while implementing interfaces.
}
Syntax of nested interface which is declared within the class
class class_name
{
...
interface nested_interface_name
{
...
}
} // Outer interface
Example:
interface Vehicle
{
// Nested interface
interface Engine
{
void start();
}
}
// Class implementing the nested interface
class Car implements Vehicle. Engine
{
public void start()
{
[Link]("Engine started");
}
public static void main(String[] args)
{
Car myCar = new Car();
[Link](); // Output: Engine started
}
}
How it works:
• Engine is a nested interface inside Vehicle.
• Car implements the nested interface using implements [Link].
• In main, we create a Car object and call start ()
void method1();
}
interface Interface2
{
void method2();
}
class MyClass implements Interface1, Interface2
{
public void method1()
{
// Implementation for method1
}
public void method2()
{
// Implementation for method2
}
}
3. Interface Extension:
• Interfaces can extend other interfaces using the extends keyword, creating a hierarchy of
interfaces.
• This allows for defining more specific behaviors or grouping related methods into a
hierarchy.
For example:
interface BaseInterface
{
void base Method();
}
interface ExtendedInterface extends BaseInterface
{
void extended Method();
}
{
// Access via interface name (recommended)
[Link]("Value is: " + [Link]);