0% found this document useful (0 votes)
2 views10 pages

Java Unit 2

This document covers fundamental concepts of object-oriented programming, including class definition, object creation, constructors, method overloading, static members, and method nesting. It also explains inheritance types, method overriding, and visibility control in Java, emphasizing the importance of encapsulation and abstraction. Key examples illustrate these concepts, showcasing how they are implemented in Java code.

Uploaded by

panditadarsh14
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Java Unit 2

This document covers fundamental concepts of object-oriented programming, including class definition, object creation, constructors, method overloading, static members, and method nesting. It also explains inheritance types, method overriding, and visibility control in Java, emphasizing the importance of encapsulation and abstraction. Key examples illustrate these concepts, showcasing how they are implemented in Java code.

Uploaded by

panditadarsh14
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit – 2

Defining a class, adding variables and methods, creating objects, accessing


class members, constructors, method overloading, static members, nesting of
method.

1. Defining a Class
A class is a blueprint or template for creating objects. It defines a new data type by
grouping data (variables) and behaviors (methods) together.
 Analogy: A "Car" blueprint is the class; the actual car you drive is the object.
2. Adding Variables and Methods
 Variables (Attributes): These represent the "state" of the object.
o Instance Variables: Unique to each object (e.g., color , speed ).
o Class Variables: Shared across all objects (using the static keyword).
 Methods (Behaviors): These are functions defined inside a class that describe
what the object can do (e.g., accelerate() , brake() ).
3. Creating Objects
An object is an instance of a class. When you create an object, the system allocates
memory based on the class definition.
 In most languages (like Java or C#), you use the new keyword: Car myCar = new Car();
4. Accessing Class Members
Members (variables and methods) are typically accessed using the dot operator
( . ).
 Example: [Link] = "Red"; or [Link]();
 Access is governed by Access Modifiers: public (accessible
anywhere), private (internal to class), and protected (internal + subclasses).
5. Constructors
In Java, a constructor is a special block of code that is automatically called when
an instance (object) of a class is created. Think of it as the "setup" phase for your
object—it ensures that the object has all the data it needs to start functioning.

Types of Constructors
1. Default Constructor
If you do not define any constructor in your class, the Java compiler automatically
inserts a hidden "Default Constructor" during compilation.

 Purpose: To initialize object members with default values (e.g., 0 for


integers, null for objects, false for booleans).
 Behavior: It takes no arguments and has an empty body.
 Vanishing Act: As soon as you write any constructor of your own, the
compiler-generated default constructor disappears.

2. No-Argument (No-Arg) Constructor


This is a constructor you write yourself that accepts no parameters.

 Difference from Default: Unlike the compiler-generated one, you can write
specific initialization logic here.
 Use Case: When you want every object of a class to start with the same
predefined values.

Example:

Java
class Car {
String engineType;

// Explicit No-Arg Constructor


public Car() {
[Link] = "Petrol"; // Every new car starts as Petrol
}
}

3. Parameterized Constructor
This constructor has a specific list of parameters. It allows you to pass different
values to each object at the time of creation.

 Purpose: To provide unique data to different objects.


 Mechanism: It uses the arguments passed during the new call to assign
values to the class’s instance variables.

Example:
Java
class Student {
String name;
int rollNo;

// Parameterized Constructor
public Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}
}
// Usage: Student s1 = new Student("Alice", 101);

4. Copy Constructor
Java does not provide a built-in copy constructor (unlike C++), but you can create
one. It is a constructor that creates a new object using an existing object of the
same class.

 Purpose: To create an exact duplicate of an object's current state.


 Advantage: It provides a way to copy objects without using the clone()
method, which is often considered complex or "broken" in Java.

Example:
class Point {

int x, y;

// Standard constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}

// Copy Constructor
public Point(Point oldPoint) {
this.x = oldPoint.x;
this.y = oldPoint.y;
}
}

6. Method Overloading
This allows a class to have multiple methods with the same name, provided they
have different parameters (different type, number, or order).
 Example: print(int i) and print(String s) .
 This is a form of Compile-time Polymorphism. It makes the code more readable by
using one name for similar actions.
7. Static Members
The static keyword means the member belongs to the class itself, rather than a
specific object.
 Static Variables: One copy exists for the whole class. If one object changes it, it
changes for all.
 Static Methods: Can be called without creating an object (e.g., [Link]() ). They
can only access other static members directly.
8. Nesting of Methods
Nesting of methods occurs when one method calls another method within the same
class without using an object or the dot operator.
 Logic: When Method A is running, it triggers Method B to perform a sub-task. This
helps in "Modularization," breaking a complex task into smaller, reusable pieces.

Complete Java Program: Student Management

Java

class Student {
// 1. Instance Variables
String name;
int rollNo;
double marks;

// 2. Static Member (Shared by all objects)


static String schoolName = "Global Academy";
static int studentCount = 0;

// 3. Constructor (Parameterized)
Student(String name, int rollNo, double marks) {
[Link] = name;
[Link] = rollNo;
[Link] = marks;
studentCount++; // Increment total students every time an object is created
}

// 4. Method Overloading
// Update marks with just the value
void updateMarks(double newMarks) {
[Link] = newMarks;
}

// Update marks with a value and a bonus


void updateMarks(double newMarks, double bonus) {
[Link] = newMarks + bonus;
}

// 5. Nesting of Methods
// getGrade() is called inside displayDetails()
private String getGrade() {
if (marks >= 90) return "A";
else if (marks >= 75) return "B";
else return "C";
}

void displayDetails() {
[Link]("Roll No: " + rollNo + " | Name: " + name);
[Link]("School: " + schoolName);
// Calling another method (Nesting)
[Link]("Grade: " + getGrade());
[Link]("---------------------------");
}

// 6. Static Method
static void displayTotalStudents() {
[Link]("Total Students Enrolled: " + studentCount);
}
}

public class Main {


public static void main(String[] args) {
// Creating Objects (Instantiation)
Student s1 = new Student("Alice", 101, 88.5);
Student s2 = new Student("Bob", 102, 72.0);

// Accessing Members
[Link]();

// Using Overloaded Methods


[Link](75.0, 5.0); // Bob gets a bonus
[Link]();

// Accessing Static Member via Class Name


[Link]();
}
INHERITANCE: Inheritance is a fundamental concept in Object-Oriented
Programming (OOP) that establishes a "IS-A" relationship between classes,
allowing a new class to acquire the properties and behaviors of an existing one.

1. Extending a Class
Extending a class involves creating a subclass (child or derived class) that inherits
from a superclass (parent or base class).
When you extend a class, you create a subclass (child) based on
a superclass (parent). The subclass automatically gains all the non-private fields
and methods of the parent, but it can also add its own unique features.
 Code Reuse: You don't have to rewrite code that already exists in the parent.
 Hierarchy: It creates a natural classification of data.
 Syntax (Java/C# example):
class Animal { // Superclass
void eat() { [Link]("Eating..."); }
}

class Dog extends Animal { // Subclass


void bark() { [Link]("Barking..."); }
}
A Dog object can now call both eat() and bark() .

 Types of Inheritance:

1. Single Inheritance
In single inheritance, a subclass inherits from exactly one superclass. This is the simplest form of
inheritance.

 Structure: Class B extends Class A.


 Why use it: To add specific features to a general base class.

Example:

Java
class Animal {
void eat() { [Link]("Eating..."); }
}

class Dog extends Animal {


void bark() { [Link]("Barking..."); }
}

2. Multilevel Inheritance
This involves a chain of inheritance. A subclass acts as a superclass for another subclass.

 Structure: Class C extends Class B, and Class B extends Class A.


 Why use it: To create a hierarchy of specialized versions of an object.

Example:

Java
class Animal {
void eat() { [Link]("Eating..."); }
}

class Dog extends Animal {


void bark() { [Link]("Barking..."); }
}

class BabyDog extends Dog {


void weep() { [Link]("Weeping..."); }
}
// BabyDog has access to weep(), bark(), and eat().

3. Hierarchical Inheritance
In this type, multiple subclasses inherit from a single superclass.

 Structure: Class B extends Class A, and Class C extends Class A.


 Why use it: When different entities share common traits but behave differently.

Example:

Java
class Shape {
void draw() { [Link]("Drawing..."); }
}

class Circle extends Shape { /* specific to circle */ }


class Square extends Shape { /* specific to square */ }

4. Multiple Inheritance (Through Interfaces)


Important: Java does not support multiple inheritance with classes (i.e., one class extending
two classes) to avoid the Diamond Problem (ambiguity). However, a class can implement
multiple Interfaces.

 Structure: Class A implements Interface 1, Interface 2.


 The Diamond Problem: If Class A extended both Class B and Class C, and both had a
method display(), Class A wouldn't know which one to use. Interfaces solve this
because they (mostly) contain abstract methods without implementation.

Example:

Java
interface Printable { void print(); }
interface Showable { void show(); }

class Document implements Printable, Showable {


public void print() { [Link]("Printing..."); }
public void show() { [Link]("Showing..."); }
}

5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. Since Java doesn't
support multiple inheritance with classes, hybrid inheritance is also achieved through a
combination of Classes and Interfaces.

 Structure: A mix of Multilevel and Hierarchical inheritance.

2. Method Overriding
Method overriding occurs when a subclass provides a specific implementation for
a method already defined in its parent class. This is a core mechanism for
achieving Runtime Polymorphism.
class Robot:
def greet(self):
print("Hello, I am a robot.")

class ChatBot(Robot):
def greet(self): # Overriding the parent method
print("Hello! I am an AI-powered ChatBot. How can I help?")

 Essential Rules:
o Exact Signature: The method must have the same name, parameters, and return
type (or a covariant return type) as the parent method.
o Access Level: The subclass method cannot have a more restrictive access modifier
than the parent (e.g., a protected method cannot be made private in the subclass).
o Non-Overridable: static , final , and private methods cannot be overridden.
 Key Annotations & Keywords:
o @Override : An optional but recommended annotation that tells the compiler to
check for a matching parent method, catching typos during development.
o super : Used within an overriding method to call the original parent version before
or after adding new logic.

3. Comparison of Inheritance Concepts


Feature Method Overriding Method Overloading
Relationship Between a superclass and subclass. Within the same class.
Parameters Must be identical. Must be different.
Polymorphism Runtime (Dynamic). Compile-time (Static).
Purpose To provide a specific implementation. To increase program readability.

Final variables and method, final classes, finalizes methods,


abstract methods and classes, visibility control
In Java, these keywords and concepts act as the "rules of engagement" for how
classes and methods can be used or modified. Here is the breakdown:
1. The final Keyword
The final keyword is used to restrict the user. It can be applied to variables,
methods, and classes.
 Final Variables: Once a final variable is assigned a value, it cannot be changed (it
becomes a constant).
o Example: final int SPEED_LIMIT = 80;
 Final Methods: A method declared as final cannot be overridden by subclasses.
This is used when you want to ensure the exact implementation of a method is
preserved across all child classes.
 Final Classes: A class declared as final cannot be extended (inherited).
o Example: The String class in Java is final; you cannot create a subclass of String .
2. The finalize() Method
The finalize() method is a special method used by the Garbage Collector just before
an object is destroyed.
 Purpose: To perform cleanup operations (like closing a database connection).
 Note: It is now deprecated in modern Java (since Java 9) because it is
unpredictable and can cause performance issues. Developers are encouraged to
use try-with-resources or Cleaners instead.
3. Abstract Classes and Methods
Abstraction is about hiding implementation details and showing only
functionality.
 Abstract Methods: A method that has no body (it only has a signature). It must be
implemented by any "concrete" (non-abstract) subclass.
o Syntax: abstract void draw();
 Abstract Classes: A class that cannot be instantiated (you cannot do new MyClass() ).
It can contain both abstract methods and "regular" (concrete) methods. It serves as
a blueprint for other classes.
4. Visibility Control (Access Modifiers)
Visibility control in Java, often called Access Modifiers, determines which classes can see and
use specific members (variables, methods, constructors, or the class itself). This is the foundation
of Encapsulation, which keeps sensitive data safe from unauthorized access.

1. The Four Levels of Visibility


Visibility ranges from completely open to strictly private.
Modifier Keyword Visibility Scope Best Used For

Public public Everywhere in the entire Global APIs, utility methods, and constants.
application.

Protected protected Same package AND subclasses in Methods meant to be customized by child classes.
different packages.

Default (None) ONLY within the same package. Internal helper classes shared within a folder.

Private private ONLY within the same class. Core data fields and internal class logic.

You might also like