0% found this document useful (0 votes)
62 views11 pages

Java Classes, Objects, and Methods Guide

Module 2 covers fundamental concepts of object-oriented programming, including classes, objects, methods, constructors, and inheritance. It explains the purpose and types of variables, method overloading, and access modifiers, as well as the use of abstract classes and interfaces. Additionally, it provides examples and best practices for coding in Java, along with common exam questions and a cheat-sheet for quick reference.

Uploaded by

shreyasharma
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)
62 views11 pages

Java Classes, Objects, and Methods Guide

Module 2 covers fundamental concepts of object-oriented programming, including classes, objects, methods, constructors, and inheritance. It explains the purpose and types of variables, method overloading, and access modifiers, as well as the use of abstract classes and interfaces. Additionally, it provides examples and best practices for coding in Java, along with common exam questions and a cheat-sheet for quick reference.

Uploaded by

shreyasharma
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

Module 2 — Classes, Objects & Methods

1. Class & Object — core definitions & how they map to real life
Class (definition): A class is a blueprint or template that defines data (attributes) and
behaviors (methods) that objects of that type will have.
Think: class = cookie cutter.
Object (definition): An object is an instance of a class — a concrete item created using
the class blueprint.
Think: object = cookie created by the cutter.

Why use classes?

Encapsulate related data and operations.


Model real-world entities in code (students, cars, bank accounts).
Make code reusable and maintainable.

Simple example

class Student {

int id; // attribute (field)

String name; // attribute

void display() { // behavior (method)

[Link]("ID: " + id);

[Link]("Name: " + name);

public class Main {

public static void main(String[] args) {

Student s1 = new Student(); // create object

[Link] = 101;

[Link] = "Aarav";
[Link]();

Key points: Student = class, s1 = object, id/name are fields, display() is method.

2. Constructors — purpose, rules and types


Purpose: Special block used to initialize a newly created object (set initial values, allocate
resources, print debug info, etc.). Called automatically when new is used.
Rules:
Name must match the class name exactly.
No return type (not even void).
Can be overloaded (multiple constructors with different parameter lists).
Types of constructors:
1. Default constructor (no-arg):
If you do not define any constructor, Java provides a no-arg default constructor
that sets fields to default values (0, null, false).
If you define any constructor, Java does not auto-create the default one.
2. No-arg constructor (explicit):
3. class A {
4. A() { // explicit no-arg constructor
5. // initialization
6. }
7. }
8. Parameterized constructor:
Accepts arguments to initialize object with specific values.
9. class Test {
10. int x, y;
11. Test(int a, int b) {
12. x = a; y = b;
13. }
14. }
15. Copy constructor (convention — Java doesn't auto-create one):
You can create a constructor that accepts an object of same class to copy values.
16. class Point {
17. int x,y;
18. Point(Point p) { this.x = p.x; this.y = p.y; }
19. }

Example

Test t1 = new Test(10, 20); // calls param constructor


3. Types of Variables (scope & lifecycle)
Instance variables (non-static):
Declared inside class but outside methods.
Each object gets its own copy.
Static variables (class variables):
Declared with static.
Single shared copy for the whole class (all objects see same value).
Use when a common property shared across objects (e.g., collegeName).
Local variables:
Declared inside methods/blocks.
Scope limited to that method/block; must be initialized before use.

Example

class Student {

String name; // instance

static String college = "U A";// static

void f() {

int local = 5; // local

4. Static Methods & Static Context


Static methods belong to class, can be called without creating an object:
[Link]().
Rules / restrictions:
Static methods can directly access only static variables and other static methods.
Cannot directly access instance variables/methods (without an object).
Common use: utility/helper methods, main() must be static.

Example

class Demo {

static int count;


static void showCount() { [Link](count); }

5. Methods — syntax, return types, parameters, and categories


Syntax
returnType methodName(parameterList) {
// body
return value; // if returnType != void
}
Kinds:
Instance methods: operate on instance data (need object to call).
Static methods: belong to class.
Accessor (getter): returns private field.
Mutator (setter): modifies private field.
Void methods: perform actions, return nothing.

Example

int add(int a, int b) { return a + b; } // returns int

void print() { [Link]("hi"); } // void

6. Method Overloading (compile-time polymorphism)


Definition: Multiple methods in same class with the same name but different parameter
lists (different number/type/order).
How chosen: At compile time by matching argument types / count.
Why use: Improves readability — same action with different input types.

Rules & examples

class SumDemo {

void sum(int a, int b) { [Link](a+b); }

int sum(int a, int b, int c) { return a+b+c; }

double sum(double a, double b) { return a + b; }

Overloading cannot differ only by return type.


7. Arrays — basics, declaration, initialization & usage
Definition: A container to store multiple values of the same type in contiguous memory;
fixed length.
Characteristics:
Zero-based indexing.
Can store primitives or object references.
Size fixed once created.
Declaration forms:
int arr[]; // method 1
int[] arr; // method 2 (more common)
Creation / Initialization
int[] arr = new int[5]; // default zeros
int[] a = {1,2,3}; // literal init
Looping
for(int i=0; i<[Link]; i++) { ... }
for(int val : arr) { ... } // enhanced for

Common pitfalls

ArrayIndexOutOfBoundsException if index <0 or >= length.


Arrays fixed size — to grow use ArrayList or Vector.

8. Inheritance — concept & basic syntax


Meaning: Mechanism where a class (subclass/child) acquires fields and methods from
another (superclass/parent).
Syntax: class Child extends Parent { ... }
Benefits:
Reusability of code.
Hierarchical classification.
Single inheritance (Java): class extends only one class (but can implement many
interfaces).

Example

class Parent { void display() { [Link]("I am Parent"); } }

class Child extends Parent { void show() { [Link]("I am Child"); } }


9. Method Overriding (runtime polymorphism)
Definition: Subclass provides its own implementation for a method already defined in
superclass with the same signature (name + parameters) and same return type.
How it works: When overridden method is called on subclass object, subclass version
executes (method dispatch at runtime).
Rules:
Same signature and return type (covariant return types allowed in newer Java).
Access modifier in subclass must be same or more accessible (cannot reduce
visibility).
Cannot override final or static methods (static methods are hidden, not overridden).
If superclass method throws exceptions, overridden method cannot throw new
checked exceptions broader than those declared in base method.

Example

class Parent { void show() { [Link]("Parent"); } }

class Child extends Parent {

void show() { [Link]("Child"); } // overrides

10. super keyword — access to parent class members


Uses:
super() — call parent class constructor (must be first line in constructor).
[Link] — access parent’s field when subclass has same name field.
[Link]() — call parent class method (useful when overriding).
Common scenario: differentiate between parent and child field names.

Example

class Vehicle { int speed = 120; }

class Car extends Vehicle {

int speed = 180;

void display() {

[Link]([Link]); // prints 120

}
11. final keyword — variables, methods, classes
final variable: value cannot be changed after initialization (constant).
final double PI = 3.14159;
final method: cannot be overridden by subclasses.
final class: cannot be extended (no subclassing).
Use final to prevent modification/override when needed for security or design.

12. finalize() method (legacy cleanup hook)


Purpose: Called by the Garbage Collector before object memory is reclaimed; can be
used for cleanup (closing resources).
Signature: protected void finalize() throws Throwable
Important: Relying on finalize() is discouraged (unpredictable timing, expensive). Use try-
with-resources or explicit resource management instead. JVM may not call finalize()
promptly or at all before exit.

13. Abstract classes & abstract methods


Abstract class: declared with abstract keyword, cannot be instantiated directly.
Designed to be subclassed.
Can contain both abstract methods (no body) and concrete methods (with
implementation).
Abstract method: method without body — subclasses must override unless subclass is
also abstract.

Example

abstract class Shape {

abstract void draw(); // subclass must implement

void common() { ... } // concrete method

class Circle extends Shape {

void draw() { [Link]("draw circle"); }

}
Use cases: Provide a common template and shared code while forcing subclasses to
implement specific behaviors.

14. Access Modifiers (visibility control)


Controls which classes can access members (fields/methods/constructors).

1. private
Accessible only within the same class.
Use to hide implementation details (encapsulation).
2. Default (package-private)
No modifier specified.
Accessible within the same package.
3. protected
Accessible within same package and by subclasses (even if in different package).
4. public
Accessible from anywhere.

Quick table

Modifier Same Class Same Package Subclass (diff World


pkg)

private yes no no no

default yes yes no no

protected yes yes yes no

public yes yes yes yes

Best practice: Keep data private and expose via getters/setters.

15. Interfaces — contract for behavior & multiple inheritance


Definition: An interface is an abstract type that declares method signatures (and
constants). Classes implement interfaces and provide method bodies.
Key points:
Prior to Java 8: interfaces could only have abstract methods and public static final
fields.
From Java 8+: interfaces may include default methods (with body) and static methods.
Interfaces enable multiple inheritance of type — a class can implement multiple
interfaces.
When to use: When you want to define a behavior contract that many unrelated classes
can implement.

Example

interface Movable {

void move();

class Car implements Movable {

public void move() { [Link]("Car moves"); }

Difference: class vs interface

Class: can have state (instance variables), constructors, full implementations.


Interface: primarily method signatures; variables are implicitly public static final.

16. Relationship: class, abstract class, interface


A class can extend one class and implement multiple interfaces.
An abstract class can provide partial implementation and force subclasses to implement
abstract methods.
Interfaces are best for unrelated classes sharing behavioral contract.

17. Vectors & Collections (brief)


Vector: thread-safe, resizable array-like structure ([Link]).
Methods: add(), remove(index), size(), etc.
Older than ArrayList; synchronised methods (slower).
When to use: For dynamic-sized collections. Prefer ArrayList for non-thread-safe, better
performance.

Example
Vector<Integer> v = new Vector<>(5);

[Link](1); [Link](2);

[Link](1); // removes element at index 1

[Link](v);

18. Additional important rules & exam tips


Overloading vs Overriding
Overload = same name, different parameters (same class).
Override = same signature, subclass replaces superclass behavior (runtime).
Static methods are not overridden; they are hidden — calling [Link]() calls
compile-time resolved version.
Access modifiers rule for overriding: overridden method cannot have more restrictive
visibility.
Constructors are not inherited. Use super() to call parent constructors.
this keyword: reference to current object; this() can call another constructor in same
class.
Exception with overriding: overriding method cannot throw broader checked exceptions
than the parent method.
Arrays are fixed-size; to grow dynamically use ArrayList or Vector.
Always close resources (Scanner, DB connections) — prefer try-with-resources.

19. Common exam questions (short answers + sample points)


1. Define class and object — example.
Definition, mapping to real world, short code snippet.
2. Explain constructors and types.
Default, parameterized, copy; rules; example.
3. Difference between method overloading and overriding.
Write 3-4 bullet differences + example.
4. Explain static vs instance members.
Shared vs per-object, when to use static, examples.
5. What is super? Give use-cases.
Access parent members, call parent constructor.
6. Explain access modifiers.
Table + short explanation.
7. Explain abstract class vs interface.
Instantiation, methods, multiple inheritance aspects.
8. What is final and where to use it?
final variable/method/class, rationale.
9. Explain garbage collection and finalize().
GC cleans unused objects; finalize() deprecated pattern — use try-with-resources.

20. Short cheat-sheet (most important quick facts)


Class → blueprint; Object → instance.
Constructor name = class name; no return type.
static → class-level, shared.
private → class-only; protected → package+subclasses; default → package; public →
everywhere.
Overload → compile-time; Override → runtime.
final stops modification/extension; abstract forces subclass behavior.
Use implements for interfaces, extends for classes.

Common questions

Powered by AI

Abstract classes and interfaces allow for polymorphic behavior in Java by providing common protocols for various subclasses or implementing classes. An abstract class can have both abstract methods, which require subclass implementation, and concrete methods. This allows partial implementation while enforcing other behaviors. Interface in Java declares method signatures and constants, allowing classes to implement multiple interfaces, providing a mechanism for multiple inheritance of type. A major difference is that interfaces define a pure behavior contract for unrelated classes, whereas abstract classes are used when there is a common ancestor or state with shared code that subclasses can extend. Interfaces from Java 8+ also allow static and default methods, enhancing their functionality .

Static methods in Java belong to the class rather than any object instance and can be called without creating an object using ClassName.method(). They can only directly access static variables and other static methods, and they cannot directly manipulate instance variables or call instance methods. Instance methods, on the other hand, operate on instance data and require an object to be invoked. Static methods are commonly used for utility functions or in the 'main' method, which must be static to allow JVM loading. They differ from instance methods primarily in how they interact with class data and are a tool for when instance-specific context isn't required .

Access modifiers in Java, including private, default (package-private), protected, and public, control access to class members, aiding in encapsulation and information hiding. 'Private' restricts access to within the same class, promoting strong encapsulation for implementation details. 'Default' provides package-level accessibility. 'Protected' extends accessibility to subclasses even in different packages. 'Public' allows access from anywhere, useful for APIs and interfaces. The best practices involve keeping data private to shield implementation details, using getters/setters for controlled access, and thinking carefully about modifying visibility to maintain code integrity, security, and design clarity .

Method overloading allows multiple methods in the same class to have the same name but different parameter lists (different number, type, or order). This is a form of compile-time polymorphism, as the method to be called is resolved at compile time based on the argument types or count. For example, a 'sum' method may be overloaded to accept both integers and doubles. Method overriding occurs when a subclass provides a specific implementation of a method already declared in its superclass, with the same name and parameters. This is a form of runtime polymorphism, where the subclass version of the method is executed. Overriding allows dynamic method dispatch at runtime, exemplified by the 'show' method in a 'Child' class overriding the same method in its 'Parent' class .

The 'final' keyword in Java is used to restrict usage and enhance robustness by preventing modification. When used on variables, 'final' ensures the variable's value cannot be changed after initialization, effectively making it a constant. Final methods cannot be overridden in subclasses, which helps maintain method implementations across an inheritance hierarchy. A final class cannot be extended, preventing subclassing and ensuring the class's structure and behavior cannot be altered. These uses provide control and security over code behavior, useful in protecting sensitive code sections or creating immutable classes .

A class in object-oriented programming is a blueprint or template that defines the attributes (fields) and behaviors (methods) an object of that type will have. This can be compared to a real-world example like a 'cookie cutter' where a class is the cutter and an object is a cookie created by it. Classes encapsulate related data and operations, model real-world entities in code (like students or bank accounts), and help make code reusable and maintainable. For example, the 'Student' class defines fields like 'id' and 'name', and a method 'display' to show these details, illustrating how a class can be used to represent real-world entities .

Method overriding enables dynamic polymorphism in Java, allowing a subclass to provide a specific implementation for an inherited method. This feature allows a subclass object to execute its version of the method even when it's referenced as a superclass type. Rules for method overriding include maintaining the same method signature (name and parameter types) and covariant return types. The access modifier in the subclass method must be the same or more accessible compared to the superclass method. Overriding must respect exception handling, meaning the overriding method cannot throw broader checked exceptions than the overridden method. This mechanism facilitates runtime behavior changes and enhances extensibility .

Instance variables, declared inside a class but outside any method, are unique to each object instance, meaning each object gets its own copy. Local variables are declared inside methods or blocks and are only accessible within that block, requiring explicit initialization before use. Static variables are declared with the 'static' keyword, providing a shared single copy across all instances of a class, suitable for common properties shared across objects. These scope differences influence the design and efficiency of software, dictating appropriate use-cases where shared data consistency or isolated data handling is necessary .

Constructors are special blocks in Java used to initialize newly created objects by setting initial values or allocating resources. They are called automatically when 'new' is used. There are different types of constructors: 1) Default constructor, provided by Java if no constructor is defined; 2) No-arg constructor, explicitly defined to initialize an object with preset defaults; 3) Parameterized constructor, which accepts arguments to initialize object fields with specific values; and 4) Copy constructor, used to create a new object as a copy of an existing object. Constructors improve the robustness and flexibility of object initialization, allowing for various setup configurations .

The 'super' keyword in Java is used to access methods and fields from a superclass that might be hidden by subclass definitions. 'super()' is used to call the parent class's constructor, which must be the first line in the subclass constructor. 'super.field' and 'super.method()' are used to access fields and methods in the parent class when they are overshadowed by subclass fields or methods with the same name. This is particularly useful when implementing subclass-specific behaviors that build upon or differentiate from the parent's behavior, such as initializing subclass fields before executing the custom subclass implementation .

You might also like