Classes, Objects, Methods & Constructors in Java
Overview: If two students have the same name, they are still two separate objects.
Defining a Class, Variables, and Methods
- In Java, a Class is a user-defined blueprint or template from which individual Objects (Instances) are created.
- Fields (Instance Variables / Attributes): Represent the state or data of the object.
- Methods (Member Functions): Represent the behavior or actions that operate on that data.
Creating Objects (Instantiation) in Java
- An Object is a runtime instance of a class that occupies actual memory in the Heap.
- Declaration (
Student s1;): Declares a reference variables1in Stack memory that initially holdsnull. - Instantiation & Initialization (
s1 = new Student();): Thenewoperator dynamically allocates memory for a newStudentinstance in Heap memory, invokes the constructor… - Accessing Fields and Methods (The Dot . Operator): Once an object is created, we use the dot operator (
.) with the object reference to access its variables and methods:
View diagram · Figure 2.1: Two Steps of Creating an Object in Java (Student s1 = new Student();)
Constructors in Java
- A Constructor is a special member method of a class that is automatically called by the JVM at the exact moment an object is created…
- 4 Golden Rules of a Constructor: The constructor name must be 100% identical to the Class Name.
- A constructor must NOT have any return type, not even
void! - It is called automatically only once per object creation (
new ClassName()). - A constructor cannot be
abstract,static, orfinal.
Types of Constructors in Java (Including Copy Constructor)
- In Java, constructors are divided into 3 types:
- 1. Default (No-Argument) Constructor: A constructor that accepts zero parameters.
- Implicit Default Constructor: If you do not write any constructor in your class, the Java compiler automatically inserts a hidden no-arg constructor…
- Explicit No-Arg Constructor: Written by the programmer to set custom initial values.
- 2. Parameterized Constructor: A constructor that accepts one or more parameters.
- 3. Copy Constructor in Java: What is a Copy Constructor? A constructor that initializes a new object using the values of an already existing object of the same class…
- Important Note: Unlike C++, Java does not provide a built-in default copy constructor.
- Output: *(Note: Having multiple constructors in the same class with different parameter lists, as shown above, is called **Constructor…
View diagram · Figure 2.2: Three Types of Constructors in Java
Comparison: Constructor vs Method
- 1. Purpose: Used to initialize the state (fields) of a newly created object.
- 2. Name: Must have the exact same name as the Class.
- 3. Return Type: Has no return type (not even
void). - 4. Invocation: Invoked implicitly (automatically) by the
newkeyword. - 5. Default Provision: Compiler provides a default constructor if none is written.
- 6. Inheritance: Constructors are NOT inherited by subclasses.
Memory Allocation, Garbage Collection, Java Keywords, Access Specifiers & JDK Tools
Overview: If two references point to a student object, clearing one reference still leaves the object reachable through the other.
Memory Allocation in Java (Stack vs Heap)
- Whenever a Java program runs, the JVM divides main memory (RAM) primarily into two regions for storing variables and objects: Stack Memory…
- Stack Memory (Fast, LIFO) Stores method call frames & local primitive variables (e.g., int x = 10; )
- Heap Memory (Large, Dynamic) Stores ALL Objects created with new (e.g., new Student() at 0x4A2 )
View diagram · Figure 2.3: How Stack and Heap Memory Work Together in Java
Garbage Collection (GC) in Java
- In C/C++, programmers must manually free dynamically allocated memory using
free()ordelete. - How Does an Object Become Eligible for Garbage Collection?: An object on the Heap becomes “garbage” (eligible for GC) in 3 ways:
- Important Methods Related to Garbage Collection:
System.gc()orRuntime.getRuntime().gc(): finalize()Method:
Essential Java Keywords: this, static, and final
- A. The this Keyword:
thisis a reference variable inside an instance method or constructor that always refers to the currently calling object. - Main Uses of
this: - Resolving Shadowing (Name Conflict): Distinguishes between instance variables and local parameters when both have the exact same name (`this.rollNo =…
- Constructor Chaining (
this()): Calling one constructor from another constructor within the same class. - Passing the current object as an argument to another method.
- B. The static Keyword: The
statickeyword is used for memory management. - Static Variable (Class Variable): Only one single copy is created in the Method Area and shared among all objects of that class (e.g., `static String…
- Static Method: Can be called directly using the Class Name (
Math.sqrt(25)) without creating an object.
Access Specifiers (Access Modifiers) in Java
- Access specifiers control the visibility and accessibility of classes, variables, constructors, and methods across packages.
private: ✅ Yesdefault(No keyword): ✅ Yesprotected: ✅ Yespublic: ✅ Yesprivate: Most restrictive; accessible only within the same class (used for Encapsulation / data hiding).default(Package-Private): Applied when no keyword is written; accessible only to classes inside the same package.protected: Accessible within the same package plus inside child subclasses located in other packages.
Using the JDK Tools
- The Java Development Kit (
jdk/bin) provides command-line tools for compiling, running, documenting, inspecting, and debugging Java… - 1.
javac:javac Student.java - 2.
java:java Student - 3.
javadoc:javadoc Student.java - 4.
javap:javap java.lang.String - 5.
jar:jar cvf app.jar *.class - 6.
jdb:jdb Student
Arrays, String, StringBuffer & Wrapper Classes in Java
Overview: An array can store five marks with fixed positions.
Arrays in Java
- An Array is a fixed-size, indexed collection of homogeneous elements (elements of the same data type) stored in contiguous memory…
- Unlike C/C++, Arrays in Java are dynamically allocated Objects stored in Heap memory!
- Every array in Java has a built-in
lengthproperty (arr.length) that stores the number of elements in the array, and Java… - B. Two-Dimensional (2D) Array (Matrix): A 2D array in Java is an “array of arrays” organized into rows and columns:
String and StringBuffer Classes in Java
- In C/C++, a string is simply a
char[]array terminated by\0. - A. The String Class (Immutable Strings): Objects of the
Stringclass are Immutable (Unchangeable). - What does Immutable mean? Once a
Stringobject is created in memory, its text content cannot be modified. length():s.length()charAt(int i):s.charAt(2)substring(start, end):s.substring(0, 4)equals(String s2):s.equals("java bca")equalsIgnoreCase(s2):s.equalsIgnoreCase("java bca")
Wrapper Classes in Java
- Java is an Object-Oriented language, yet its 8 primitive data types (
int,double,char,boolean, etc.) are NOT objects—they… byte:Byteshort:Shortint:Integer(Full word!)long:Longfloat:Floatdouble:Double- Key Uses of Wrapper Classes + Autoboxing & Unboxing: Autoboxing: The automatic conversion of a primitive data type into its corresponding Wrapper Object by the Java compiler.
View diagram · Figure 2.4: Converting Between Primitives and Wrapper Objects
Inheritance: Super Class, Sub-Class, Method Overloading vs Overriding & Abstract Classes
Overview: A method with the same name but a different parameter list is an overload.
Inheritance Basics: Super Class and Sub-Class
- Inheritance is one of the four core pillars of OOPs in which a new class acquires the fields and methods of an existing class.
- Super Class (Parent Class / Base Class): The existing class whose properties and methods are inherited.
- Sub-Class (Child Class / Derived Class): The new class that inherits from the super class and can also add its own unique fields and methods.
extendsKeyword: Used to create a subclass in Java.- Why Use Inheritance?: Code Reusability: Write common code once in the Super Class and reuse it across multiple Sub-Classes without copy-pasting.
- Method Overriding (Runtime Polymorphism): Allows a subclass to provide a specialized implementation of a method defined in its superclass.
Types of Inheritance in Java
- Java supports 3 types of inheritance directly through classes:
- 1. Single Inheritance Class B extends Class A (One Parent → One Child)
- 2. Multilevel Inheritance Class C extends B, and Class B extends A (Grandparent → Parent → Child)
- 3. Hierarchical Inheritance Classes B, C, and D all extend the same Parent Class A
- Why doesn’t Java support Multiple Inheritance through Classes?
- Suppose Class
Ctries to inherit from both ClassAand ClassB(class C extends A, B), and bothAandBhave a method with the…
View diagram · Figure 2.5: Types of Inheritance Supported by Classes in Java
The super Keyword in Java
- Whenever a subclass wants to refer to its immediate parent class (Super Class), it uses the
superkeyword. - 3 Uses of the super Keyword:
super.variableName: Accesses a parent class instance variable when the child class has a variable with the same name. super.methodName(): Calls the parent class version of an overridden method.super(...)(Constructor Call): Invokes the constructor of the parent class from inside the child class constructor.
Method Overloading vs Method Overriding
- Students often confuse Method Overloading and Method Overriding.
- A. Method Overloading (Compile-Time Polymorphism): Defining multiple methods with the exact same name inside the same class, provided their parameter lists are different…
- Note: Overloading cannot be achieved by changing only the return type!
- B. Method Overriding (Runtime Polymorphism): When a Sub-Class defines a method with the exact same name, exact same parameters, and same return type as a method already…
- 1. Definition: Multiple methods with the same name but different parameters in the same class.
- 2. Where It Occurs: Within the same class.
- 3. Parameters: Parameter list MUST be different.
- 4. Return Type: Can be the same or different.
Abstract Classes and Abstract Methods
- Sometimes a Super Class is so general that it only defines what an action is, while leaving how to perform it to its child classes.
- Rules of an abstract Class in Java: Declared using the
abstractkeyword (abstract class Shape). - Cannot be instantiated: You cannot create an object of an abstract class (
new Shape()gives a compile error). - Can contain both:
- Abstract Methods: Methods declared without a body (
abstract void calculateArea();). - Concrete (Normal) Methods: Regular methods with a body, plus constructors and instance variables.
- Any Sub-Class that extends an abstract class must override and implement all its abstract methods (or declare itself
abstract).
Interfaces in Java: Defining, Implementing, Variables & Extending Interfaces
Overview: A payment screen can depend on a Payment interface with a pay method.
What is an Interface in Java?
- An Interface in Java is a blueprint of a class that acts as a 100% pure contract specifying what a class must do, but not how it…
- Two Major Reasons Why Interfaces Exist in Java: To achieve Full (100%) Abstraction and loose coupling.
- To support Multiple Inheritance in Java safely (a single class can implement multiple interfaces at the same time!).
Defining an Interface & Variables in Interfaces
- An interface is declared using the
interfacekeyword instead ofclass. - Automatic Compiler Rules Inside an Interface: Variables in Interfaces: Every variable declared inside an interface is implicitly
public static final(a global constant!). - Methods in Interfaces: Every classic method declared inside an interface is implicitly
publicandabstract(no method body). - Like an abstract class, an interface cannot have constructors and cannot be instantiated directly (
new Printable()is invalid).
Implementing and Applying Interfaces
- To use an interface, a class uses the
implementskeyword (instead ofextends) and must provide concrete bodies for all abstract methods… - Important Rule: Because interface methods are implicitly
public, when a class implements an interface method, it **MUST declare the method…
Achieving Multiple Inheritance Using Interfaces
- In Java, a class cannot extend more than one class (
class C extends A, Bis illegal), **but a single class CAN implement multiple interfaces…
View diagram · Figure 2.6: Multiple Inheritance in Java Using Interfaces
Extending Interfaces (Interface Inheritance)
- One interface can inherit from another interface using the
extendskeyword! - Golden Keyword Rules to Remember (extends vs implements): Class → Class: uses
extends(class B extends A) - Class → Interface: uses
implements(class B implements I1, I2) - Interface → Interface: uses
extends(interface I2 extends I1)
Comparison: Abstract Class vs Interface
- This is one of the most important 8-mark comparison questions in Unit 2 of DAVV BCA exams!
- 1. Keyword Used: Declared using
abstract class. - 2. Multiple Inheritance: A subclass can extend only ONE abstract class.
- 3. Types of Methods: Can have both abstract methods and normal concrete methods with bodies.
- 4. Variables (Fields): Can have
private,protected, non-final, and non-static instance variables. - 5. Constructors: Can have constructors (called via
super()when a subclass is instantiated). - 6. Access Modifiers: Methods and variables can be
public,protected,private, ordefault.