Unit 2 Notes
Unit 2 Notes
Unit 2 Notes
Introduction to Classes
In object-oriented programming (OOP), a class serves as a blueprint for creating objects
(instances). It defines the structure and behavior (data and methods) that the objects will
have.
Key Concepts:
Class: A template or blueprint used to create objects. It encapsulates data (attributes)
and behavior (methods).
Object: An instance of a class. It has a unique identity, state, and behavior.
1. CLASS DECLARATION
In Java (or most OOP languages), a class is declared with a specific syntax, and you can
control its visibility and accessibility using access modifiers.
Modifier: Optional keyword(s) that define the accessibility (public, private, protected) or
behavior (e.g., abstract, final) of the class.
ClassName: The name of the class, which should typically follow CamelCase
convention.
Example:
// constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
// method (behavior)
public void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
Fields: model and year that define the state of a car object.
Constructor: A method that initializes the state of the object when it is created.
Method: displayInfo() that defines the behavior of the class.
2. CLASS MEMBERS
Fields
Fields, also known as attributes or properties, store data specific to an object. For
example, a Car class might have fields for model , color , and year .
Methods
Methods define the actions or behavior of a class. They usually operate on the fields of the
class and can modify or retrieve the data stored in them.
Constructors
A constructor is a special method used to initialize objects. It’s called when an object is
created. In most languages like Java, the constructor has the same name as the class.
Example:
public class Car {
String model;
int year;
// Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
ClassName : The name of the class from which the object is created.
objectName : The name of the object.
new : The keyword used to allocate memory for the object.
ClassName(parameters) : Calls the constructor to initialize the object.
Example:
This creates an object myCar of the class Car with model as "Tesla" and year as 2023 .
Shallow Copy: In a shallow copy, the new object references the same memory location
as the original object. Therefore, changes to one object will affect the other.
System.out.println(obj2.name);
System.out.println(obj2.age);
obj2.attendance();
}
}
Deep Copy: In a deep copy, a new object is created with its own memory space, and
the fields of the original object are copied into this new object. Changes made to one
object do not affect the other.
System.out.println(obj2.name);
System.out.println(obj2.age);
}
}
5. CONSTRUCTORS
A constructor is a special method in a class that is called automatically when an object of
the class is created. It is used to initialize the object’s instance variables or provide default
values. The name of the constructor is always the same as the class name, and it doesn’t
have a return type, not even void .
Constructors ensure that objects start in a consistent state by initializing their instance
variables.
Without constructors, objects would need to be manually initialized using methods after
creation, which could lead to uninitialized or inconsistent data.
Example of a Simple Constructor:
public Student()
{
this.name = "Raja";
this.age = 44 ;
}
Types of Constructors:
- Default Constructor:
If you do not provide any constructor, the compiler provides a default constructor that
initializes the object with default values (like null for strings, 0 for integers).
Example:
public Student()
{
this.name = "Raja";
this.age = 44 ;
}
- Parameterized Constructor:
A constructor that accepts parameters to initialize the object with specific values.
Example:
OVERLOADED CONSTRUCTOR:
Constructor overloading allows you to create multiple constructors within a class, each
with different numbers or types of parameters. This provides flexibility in object creation, as
different constructors can handle different ways of initializing an object.
Purpose: Overloading constructors is useful when you want to provide multiple ways to
create an object based on different sets of input data.
public Student()
{
this.name = "Alice";
this.age = 10 ;
}
public Student(String x)
{
this.name = x;
this.age = 20 ;
}
obj1.display();
obj2.display();
obj3.display();
}
Advantages of Constructor Overloading:
Flexibility: Multiple constructors allow you to initialize objects in different ways without
the need for multiple class definitions.
Convenience: You can create objects with varying levels of data, allowing optional or
default values for certain attributes.
6. this KEYWORD
The this keyword in Java is a reference to the current object (the instance of the class
that is executing the code). It is commonly used to avoid ambiguity between class fields
(instance variables) and parameters with the same name.
Example:
In this example, this.model refers to the instance variable model , while model (without
this ) refers to the parameter of the constructor. Without this , there would be ambiguity
between the parameter and the instance variable.
7. NESTED CLASS
In Java, nested classes are classes that are defined within another class. They provide a
way to logically group classes that are only used in one place, which can lead to more
readable and maintainable code. There are two main types of nested classes:
class Outer
{
String name = "Raja";
static int age = 55 ;
2 Inner Classes
An inner class is a non-static nested class that is associated with an instance of the outer
class. Inner classes can access both static and non-static members of the outer class,
including private ones.
class Outer
{
String name = "Raja";
static int age = 55 ;
class Inner
{
void display()
{
System.out.println(name);
System.out.println(age);
}
}
class Outer
{
void outermethod()
{
String name = "Raja";
class LocalInner
{
void display()
{
System.out.println(name);
}
}
change(num);
System.out.println(num);
}
}
class Person
{
int num = 55 ;
}
change(obj);
System.out.println(obj.num);
}
}
9. ACCESS CONTROL FOR CLASS MEMBERS
In Java, access control modifiers determine the visibility and accessibility of class
members (variables and methods) from outside the class. This is a key part of
encapsulation, one of the fundamental principles of object-oriented programming (OOP),
where data is hidden and only accessible through well-defined interfaces.
In this example, both the model variable and the start() method can be accessed
from any class.
private: When a class member is declared as private , it can only be accessed within
the class in which it is defined. This is the most restrictive access level and is often
used to enforce encapsulation and protect sensitive data from external modification.
In this case, model and start() cannot be accessed directly from outside the Car
class.
protected: A protected class member is accessible within the same package and by
subclasses of the class, even if they are in different packages. This modifier is useful
when you want to allow controlled access to inherited members in subclasses.
Here, model and start() can be accessed by subclasses or any class in the same
package.
default (no modifier): If no access modifier is specified, the member has default
(package-private) access. This means it can be accessed only within the same
package, but not from outside the package.
void start() {
System.out.println("Car started");
}
}
Both model and start() are accessible to other classes within the same package but
not to classes in different packages.
10.METHODS IN JAVA
What are Methods?
A method is a block of code that performs a specific task and can be called upon
whenever needed. Methods help in organizing code, improving readability, and
facilitating code reusability.
Defining Methods
Method Signature:
The method signature consists of the method name and the parameter list. It uniquely
identifies the method within its class.
Return Types:
A method can return a value, indicated by its return type. If a method does not return
any value, its return type is void .
Parameters:
Parameters are the inputs to the method. They are defined within parentheses in the
method declaration. A method can have zero or more parameters.
Method Body:
The body of the method contains the code that defines what the method does,
enclosed within curly braces {} .
class Calculator {
// Method to add two numbers (returns an integer)
public int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
class Abc
{
String name = "Raja" ;
}
class Def
{
void display(Abc obj)
{
System.out.println(obj.name);
}
}
Let's delve into access control in Java methods and the concept of recursive methods.
These are essential components of Java programming that help manage data encapsulation
and solve problems efficiently.
Access Modifiers:
1. Public:
The method is accessible from any other class in any package.
Use it for methods that need to be widely accessible.
public class MyClass {
public void myMethod() {
// Method implementation
}
}
2. Private:
The method is accessible only within its own class.
Use it to hide implementation details and protect sensitive data.
3. Protected:
The method is accessible within its own package and by subclasses (even if they
are in different packages).
Use it when you want to allow controlled access to subclasses.
4. Default (Package-Private):
If no access modifier is specified, the method is accessible only within its own
package.
Use it for methods that should be accessible to other classes in the same package
but hidden from the outside world.
// Protected method
protected void display() {
System.out.println("Name: " + name + ", Age: " + age + ", City: " +
city);
}
}
A recursive method is a method that calls itself to solve a problem. It is often used to
solve problems that can be broken down into smaller, similar sub-problems.
1. Base Case: The condition under which the recursion ends. It prevents infinite
recursion.
2. Recursive Case: The part of the method where the method calls itself with modified
arguments.
Method nesting refers to the practice of calling one method from another method within
the same class. This technique allows for better organization of code and can help
break complex tasks into simpler, reusable methods.
Practical Applications:
Code Reusability: You can call common functionalities in multiple methods without
repeating code.
Modularity: It helps in structuring your code, making it easier to understand and
maintain.
Clear Logic Flow: It allows for a clearer logical flow in your program by breaking down
operations into smaller, more manageable parts.
In this example, FinalClass is declared as final , so no other class can extend it.
void display() {
System.out.println("MAX_VALUE: " + MAX_VALUE);
// MAX_VALUE = 200; // Compilation error
}
}
In this example, MAX_VALUE is a constant, and any attempt to reassign it will result in a
compilation error.
2. Static Attributes
The static keyword in Java is used to define class-level variables and methods that
belong to the class itself rather than to any specific instance. This means that static variables
and methods can be accessed without creating an instance of the class.
class Counter {
static int count = 0; // Static variable
public Counter() {
count++; // Increment count for each object created
}
class MathUtil {
// Static method to calculate square
public static int square(int number) {
return number * number;
}
}