0% found this document useful (0 votes)
8 views41 pages

Why Java is Not Purely Object-Oriented

Uploaded by

MAHEE JAISWAL
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)
8 views41 pages

Why Java is Not Purely Object-Oriented

Uploaded by

MAHEE JAISWAL
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

Java is not a purely object-oriented programming language because it includes features from procedural

programming as well. While Java strongly supports OOP principles (such as encapsulation, inheritance, and
polymorphism), it also allows procedural programming features, making it a hybrid language rather than a
pure OOP language.

Why Java is Not a Pure OOP Language?

1.​ Primitive Data Types (int, char, float, etc.)​

○​ Java supports primitive types, which are not objects. Pure OOP languages (like Smalltalk) treat
everything as an object.

Example:​
java​
CopyEdit​
int x = 10; // Not an object, directly stored in memory

○​
2.​ Static Methods​

○​ Java allows the use of static methods inside a class, which can be called without creating an
object.

Example:​
java​
CopyEdit​
class MathUtil {
static int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
int sum = [Link](5, 10); // No object creation needed
}
}

○​
3.​ Top-Level Procedural Code in main Method​

○​ The main method in Java can contain procedural-style code (without objects).

Example:​
java​
CopyEdit​
public class Test {
public static void main(String[] args) {
[Link]("Hello, World!"); // Procedural-style execution
}
}

○​
4.​ Java Supports Static Variables​

○​ Static variables belong to a class rather than an object, breaking the OOP principle of
encapsulation.

Example:​
java​
CopyEdit​
class Counter {
static int count = 0; // Shared by all instances
}

○​
5.​ Use of Packages and Procedural Approach​

○​ Java supports package-based modular programming, which is often procedural in nature.

Pure OOP Languages (for Comparison)

Languages like Smalltalk and Ruby are considered pure OOP because:

●​ Everything (including numbers, functions, and classes) is an object.


●​ There are no primitive data types.
●​ Methods are strictly associated with objects.

Conclusion

Java follows OOP principles but is not purely object-oriented because it allows procedural programming
elements, primitive data types, and static methods. It is better classified as a multi-paradigm (hybrid)
programming language, supporting both OOP and procedural programming.
Wrapper Classes in Java

Wrapper classes in Java are used to convert primitive data types into objects. Each primitive type has a
corresponding wrapper class in the [Link] package.

List of Wrapper Classes


Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long
float Float

double Double

char Character

boolean Boolean

Key Features of Wrapper Classes


Autoboxing & Unboxing – Automatically converts between primitives and objects.​
java​
CopyEdit​
int a = 10;
Integer obj = a; // Autoboxing (primitive to object)
int b = obj; // Unboxing (object to primitive)

1.​
2.​ Useful in Collections – Collections (like ArrayList) work with objects, not primitives.
3.​ Provides Utility Methods – Wrapper classes have methods for conversions and operations (e.g.,
[Link]("123")).

Example Usage
java
CopyEdit
public class WrapperExample {
public static void main(String[] args) {
Integer num = [Link](100); // Creating wrapper object
int value = [Link](); // Converting back to primitive
[Link]("Wrapper Object: " + num);
[Link]("Primitive Value: " + value);
}
}
Access Specifiers in Java

Access specifiers in Java define the visibility and accessibility of classes, methods, and variables. There
are four types of access specifiers:

Access Scope Scope within Scope in Subclass Scope in Other


Specifier within Package (Different Package) Classes (Different
Class Package)

Private ✅ Yes ❌ No ❌ No ❌ No
Default (No ✅ Yes ✅ Yes ❌ No ❌ No
keyword)

Protected ✅ Yes ✅ Yes ✅ Yes ❌ No


Public ✅ Yes ✅ Yes ✅ Yes ✅ Yes
Key Points:

1.​ private – Accessible only within the same class.


2.​ Default (No modifier) – Accessible within the same package.
3.​ protected – Accessible within the same package and subclasses.
4.​ public – Accessible from anywhere in the program.

Example Code:

class Example {
private int a = 10; // Private
int b = 20; // Default
protected int c = 30; // Protected
public int d = 40; // Public
}

Each access specifier controls data security and encapsulation in Java programs.

Constructor and Destructor in Java

1. Constructor
A constructor is a special method in Java that is used to initialize objects. It has the same name as the class
and does not have a return type.

Feature Constructor

Purpose Initializes objects of a class.

Name Same as the class name.

Return Type No return type (not even void).

Types Default Constructor, Parameterized Constructor, Copy Constructor (not


built-in in Java).

Invocation Automatically called when an object is created.

Example of Constructor
class Example {
int x;

// Constructor
Example(int value) {
x = value;
[Link]("Constructor Called! Value: " + x);
}

public static void main(String[] args) {


Example obj = new Example(10); // Constructor is invoked
}
}

2. Destructor in Java (Garbage Collection)

Java does not have a destructor like C++, as it uses Garbage Collection (GC) to automatically free memory
when objects are no longer needed. The finalize() method is sometimes used as a destructor alternative,
but it is not reliable.

Feature Destructor (Garbage Collector)

Purpose Frees memory occupied by objects.

Implementation Java does not have destructors but relies on Garbage


Collection.

Invocation Called automatically when no references to an object exist.


Alternative finalize() method (not recommended in modern Java).

Example of Garbage Collection in Java


class Example {
// Destructor alternative
protected void finalize() {
[Link]("Object is being destroyed!");
}

public static void main(String[] args) {


Example obj = new Example();
obj = null; // Marking object for garbage collection
[Link](); // Requesting garbage collection
}
}

Key Differences Between Constructor and Destructor


Feature Constructor Destructor (Garbage Collector)

Purpose Initializes objects Frees memory occupied by objects

Execution Called when an object is Called when an object is no longer


Time created referenced

Invocation Automatically during object Automatically by Java’s garbage collector


creation

Defined By Yes, explicitly defined No, Java handles memory cleanup


User automatically

Conclusion

●​ Constructors are essential for object initialization.


●​ Destructors are not present in Java; instead, Garbage Collection manages memory automatically
Q- Outline the significance of Super keyword in Java when working with constructors. 2025 (5M)
Q- Infer about the various ways to initalize an object for a class. 2025 (6 M)
—---------------------------------------------
Q- Describe about the methods in Java Object class. 2024 (5 M)

Methods in Java Object Class

1.​ clone()​

○​ Used to create and return a copy of the current object.​

○​ The class must implement the Cloneable interface.​

○​ Performs shallow copy by default.​

2.​ equals(Object obj)​

○​ Compares the current object with another for equality.​

○​ By default, compares memory addresses.​

○​ Can be overridden to compare object content.​

3.​ hashCode()​

○​ Returns an integer hash code for the object.​

○​ Used in hash-based collections like HashMap.​

○​ Should be overridden along with equals() for consistency.​

4.​ toString()​

○​ Returns a string representation of the object.​

○​ By default, shows class name and memory hash.​

○​ Commonly overridden for meaningful output.​

5.​ getClass()​

○​ Returns the runtime class of the object.​

○​ Useful for reflection and class-level information access.


Q- Provide eamples to demonstrate the various ways for importing the packages in Java. 2024(5 M)
Summary

●​ import [Link]; → imports a single class​

●​ import package.*; → imports all classes​

●​ [Link] → uses fully qualified name, no import needed​

●​ import static [Link]; → imports static members


Q - Develop a scenario where the use of packages is crucial for code organization and
understandability.
2024 ( 9 M)
Q- Paraphrase about the different types of Constructors in Java. 2024 (6 M)
Question 1:​
Outline the significance of super keyword in Java when working with constructors. (5 Marks)

Answer:

The super keyword in Java plays a vital role in constructor chaining when working with inheritance. Its
significance includes:

1.​ Calling Parent Class Constructor:​


super() is used to explicitly call the constructor of the immediate superclass. This must be the first
statement in the subclass constructor.​

2.​ Ensures Proper Initialization:​


It helps in initializing the fields of the parent class before executing the subclass-specific logic,
ensuring the inheritance chain is correctly initialized.​

3.​ Supports Constructor Overloading:​


super can be used to call a specific overloaded constructor of the superclass by passing appropriate
arguments like super(int x).​

4.​ Avoids Redundancy:​


By calling the parent constructor, we avoid duplicating code that initializes common fields or sets up
shared behavior.​

5.​ Compilation Requirement:​


If the parent class doesn’t have a no-argument constructor and the subclass doesn’t explicitly call
super(...), it results in a compilation error.
Question 2:​
Describe the methods in Java's Object class. (5 Marks)

Answer:

The Object class is the root class of all Java classes, and it provides several important methods that can be
used or overridden in user-defined classes:

1.​ equals(Object obj)​

○​ Compares two objects for equality.​

○​ Default behavior checks reference equality, but can be overridden for logical equality.​

2.​ toString()​

○​ Returns a string representation of the object.​

○​ Default: class name + hashcode; often overridden for meaningful output.​

3.​ hashCode()​

○​ Returns an integer hash code value for the object.​

○​ Must be consistent with equals() when overridden.​

4.​ clone()​

○​ Creates and returns a copy of the object.​

○​ Requires implementing Cloneable interface and handling


CloneNotSupportedException.​

5.​ finalize() (Deprecated in Java 9)​

○​ Called by garbage collector before object destruction.​

○​ Used for cleanup, but not recommended in modern Java.​

6.​ getClass()​

○​ Returns the runtime class of the object.​

○​ Useful for reflection and debugging.​


7.​ wait(), notify(), notifyAll()​

○​ Used for thread communication in synchronized blocks or methods.​

○​ Helps manage multithreaded access to shared resources.​

These methods provide foundational behavior for all Java objects, supporting features like object comparison,
cloning, synchronization, and runtime type identification.

—-----------------------------------------
Question 3:​
Provide examples to demonstrate the various ways for importing the packages in Java. (5 Marks)

Answer:

In Java, packages can be imported in several ways to access classes and interfaces. Below are the main
methods with examples:
Question 6:​
Develop a scenario where the use of packages is crucial for code organization and understandability.
(9 Marks)

Answer:

Scenario: Student Management System

Let’s say you are building a simple Student Management System. The system has features to manage
students, courses, and utilities for printing details. Without packages, all classes would be in one place,
making it messy and hard to understand.

Using Packages for Better Organization:

We can organize the code using three packages:

1.​ student – Handles student-related data​

2.​ course – Manages course information​

3.​ util – Contains utility classes like printing details

Common questions

Powered by AI

Access specifiers in Java determine the visibility and accessibility of classes, methods, and variables, which enhances data security and encapsulation. Private specifiers restrict access to within the same class, protecting internal data structures. Defaults allow package-level visibility, protected access extends to subclasses promoting inheritance, and public specifiers permit universal access, facilitating API exposure. These control mechanisms ensure that only necessary components are exposed and controllable by appropriate segments of the program, maintaining structure and preventing unintended interactions .

The use of primitive data types in Java means it does not adhere to the object-oriented principle that everything should be an object. In fully object-oriented languages like Smalltalk, even simple values are treated as objects. Java's primitive types are stored directly in memory, contradicting the concept of object manipulation and encompassing methods that are attached to objects, affecting its classification as a non-pure OOP language .

In Java, packages can be imported using several methods, impacting how classes are accessed. The 'import package.ClassName;' imports a single class explicitly. 'import package.*;' allows the import of all classes within a package, which is convenient but can lead to namespace pollution. Using 'package.className' fully qualifies the class without requiring import statements, useful in avoiding conflicts. 'import static package.ClassName.member;' imports static members for direct access. These import strategies offer flexibility in organizing and accessing Java classes efficiently .

The Object class in Java, being the superclass of all classes, provides essential methods that foster fundamental behaviors. Methods like 'equals' and 'hashCode' enable object comparison and usage in hash-based collections. 'toString' offers a default string representation, often overridden for meaningful descriptions. 'clone' allows object copying, contingent upon implementing 'Cloneable'. 'getClass' aids runtime class discovery. Finally, 'wait', 'notify', and 'notifyAll' support thread synchronization. These methods ensure consistent functionality and integration across various parts of Java programs .

Java is not a purely object-oriented language because it incorporates both object-oriented and procedural programming features. It supports primitive data types like 'int' or 'char' that are not objects, uses static methods and variables, allows the main method to execute procedural code, and supports package-based modular programming that often follows procedural design .

The 'super' keyword in Java is crucial for constructor chaining and inheritance as it explicitly calls the constructor of an immediate superclass. This ensures proper initialization of the object hierarchy by allowing the parent class's constructor to execute before the subclass specific logic. It avoids redundancy by maintaining shared initializations in a single superclass and prevents compilation errors when the parent constructor requires parameters and is not a no-argument constructor. 'Super' thus maintains consistent and efficient resource allocation throughout the inheritance chain .

Java does not implement destructors as seen in languages like C++. Instead, it relies on automatic garbage collection to manage memory. The garbage collector frees memory by destroying objects no longer referenced in the program. While Java provides the 'finalize' method as an alternative to destructors, it is deprecated due to its unpredictability and overhead. Developers are encouraged to manage resources explicitly using try-with-resources for closing resources like streams, reinforcing the shift towards reliable, manual resource management and avoiding reliance on 'finalize' .

Wrapper classes in Java facilitate object-oriented principles by allowing primitive data types to be treated as objects. These classes enable autoboxing and unboxing operations to automatically convert between primitive types and their corresponding objects, making it possible for primitives to interact with Java's OOP features, such as collections, which require objects rather than primitive data types .

Organizing Java code using packages is crucial for maintaining code clarity, modularity, and ease of maintenance. Packages group related classes and interfaces, which simplifies namespace management and avoids naming conflicts. They enable encapsulation by defining access specifiers at the package level and enhance application scalability by allowing logical separation of functionalities, like separating data handling from user interface logic in a complex system. This structured approach promotes productivity by improving code readability and facilitating collaborative development and code reuse .

Imagine developing a library system where a 'Book' class needs to handle various use cases such as creating books with just a title, or with title, author, and year published for detailed records. Constructor overloading allows different ways to instantiate 'Book' objects based on available information. For instance, 'Book(String title)' initializes a minimal book record, whereas 'Book(String title, String author, int year)' stores detailed bibliographic information, enhancing flexibility and accommodating scenarios with variable data input .

You might also like