Unit 2 of 4 · M.Sc IT Sem 4

Unit 2: Classes, arrays and inheritance

Java Technologies notes · PTU syllabus (PGCA1939)

4 min read14 topics9 exam questions
On this page
  1. Unit summary
  2. Classes and objects
  3. Creating objects
  4. Modifiers and passing arguments
  5. Constructors
  6. Constructor and method overloading
  7. Static members
  8. Garbage collection
  9. Arrays
  10. String handling classes
  11. Inheritance, overriding and polymorphism
  12. Abstract and final classes
  13. Abstract classes
  14. Interfaces
  15. Packages
  16. Key terms
  17. Quick revision
  18. Important questions

Unit summary

Classes, arrays and inheritance are the building blocks of Java programs. This unit covers classes and objects, modifiers, argument passing, constructors and overloading, static members, garbage collection, arrays, string handling, inheritance, overriding, polymorphism, abstract and final classes, packages and interfaces.

After this unit you can

  • Define classes, objects, constructors and static members
  • Use arrays and string handling classes
  • Apply inheritance, overriding and polymorphism
  • Use abstract classes, interfaces and packages

PTU syllabus topics

  • OOP basics
  • classes and objects
  • modifiers
  • passing arguments
  • constructors and overloading
  • static class members
  • garbage collection
  • arrays (single/multi-dimensional)
  • string handling classes
  • inheritance basics
  • overriding
  • polymorphism
  • abstract and final classes
  • packages and interfaces
ComparisonAbstract class vs interface
Abstract class
Interface

Methods

Abstract and concrete

Abstract, default and static

Variables

Any

Constants only (public static final)

Inheritance

extends one class

implements many interfaces

Use

Shared base with common code

Common contract across unrelated classes

1

Topic 1

Classes and objects

javaclass Student {
    private int roll;              // instance variables (fields)
    private String name;
    private double marks;

    void setData(int r, String n, double m) { roll = r; name = n; marks = m; }
    String grade() { return marks >= 75 ? "A" : marks >= 60 ? "B" : "C"; }
    void show() { System.out.println(roll + " " + name + " " + grade()); }
}
  • Access modifiers: private (class only), default (package), protected (package and subclasses), public (everywhere).
2

Topic 2

Creating objects

javaStudent s1 = new Student();        // new allocates memory on the heap; s1 holds a reference
s1.setData(101, "Aman", 82);
s1.show();
Student s2 = s1;                   // both refer to the same object
3

Topic 3

Modifiers and passing arguments

ComparisonAccess modifiers
Same class and package
Subclass elsewhere / other packages

private

Class only

No / No

default

Yes

No / No

protected

Yes

Yes / No

public

Yes

Yes / Yes

  • Java is always pass-by-value: primitives copy the value; for objects the reference is copied, so the method can change the object's fields but not make the caller's variable point elsewhere.
4

Topic 4

Constructors

javaclass Rectangle {
    int length, width;
    Rectangle() { this(1, 1); }                          // default constructor calls another
    Rectangle(int l, int w) { length = l; width = w; }   // parameterised
    Rectangle(Rectangle r) { this(r.length, r.width); }  // copy-style constructor
    int area() { return length * width; }
}
  • A constructor has the class name and no return type, runs automatically on new, and initialises the object. If none is written, Java supplies a default constructor. this refers to the current object.
5

Topic 5

Constructor and method overloading

javaclass Calc {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}
  • Same method name, different parameter lists (number, type or order); resolved at compile time — compile-time polymorphism.
6

Topic 6

Static members

javaclass Counter {
    static int count = 0;          // one copy shared by all objects
    Counter() { count++; }
    static int getCount() { return count; }   // called as Counter.getCount()
    static { System.out.println("Static block runs once when the class loads"); }
}
  • Static methods can access only static data directly and cannot use this. Math.sqrt() and Integer.parseInt() are static methods.
7

Topic 7

Garbage collection

  • Objects with no live references become eligible for garbage collection; the JVM reclaims memory automatically. System.gc() only requests it. Generational collectors (G1) separate young and old objects.
8

Topic 8

Arrays

javaint[] a = new int[5];                       // one-dimensional
int[] b = {4, 9, 1, 7};
java.util.Arrays.sort(b);
System.out.println(b.length);               // 4

int[][] m = {{1, 2, 3}, {4, 5, 6}};         // two-dimensional
int[][] jag = new int[3][];                 // jagged: rows of different lengths
jag[0] = new int[1]; jag[1] = new int[2]; jag[2] = new int[3];
for (int[] row : jag) System.out.println(row.length);
9

Topic 9

String handling classes

javaString s = "Synetic";
s.length(); s.charAt(0); s.toUpperCase(); s.substring(0, 3);   // "Syn"
s.indexOf("t"); s.equals("synetic"); s.equalsIgnoreCase("SYNETIC");
s.replace('S', 's'); s.contains("net"); s.compareTo("Apple");
String t = s.concat(" School");            // Strings are immutable

StringBuilder sb = new StringBuilder("SBS");  // mutable
sb.append(" Ludhiana").reverse();

import java.util.Vector;
Vector<Integer> v = new Vector<>();         // growable, synchronised array
v.add(10); v.add(20); v.add(1, 15);         // [10, 15, 20]
v.remove(Integer.valueOf(20));
System.out.println(v.size() + " " + v.get(0));
  • String vs StringBuffer/StringBuilder: String is immutable; StringBuffer is mutable and thread-safe; StringBuilder is mutable and faster. Vector vs ArrayList: Vector is synchronised (legacy); ArrayList is usually preferred.
10

Topic 10

Inheritance, overriding and polymorphism

javaclass Person {
    protected String name;
    Person(String n) { name = n; }
    void display() { System.out.println("Name: " + name); }
}
class Employee extends Person {
    double salary;
    Employee(String n, double s) { super(n); salary = s; }   // call parent constructor
    @Override
    void display() {                                         // method overriding
        super.display();
        System.out.println("Salary: " + salary);
    }
}
Person p = new Employee("Riya", 50000);
p.display();          // dynamic method dispatch: Employee's version runs
ClassificationTypes of inheritance in Java
Inheritance
  • Single

    B extends A

  • Multilevel

    C extends B, B extends A

  • Hierarchical

    B and C both extend A

  • Multiple

    Not with classes; achieved with interfaces

  • Overriding: same signature in the subclass; decided at run time — run-time polymorphism.
11

Topic 11

Abstract and final classes

Key termsUses of final
final variable
Constant — value cannot change
final method
Cannot be overridden
final class
Cannot be extended — e.g., String
Abstract class (related)
Declared abstract; cannot be instantiated; may have abstract methods that subclasses must implement
12

Topic 12

Abstract classes

javaabstract class Shape { abstract double area(); }
class Circle extends Shape {
    double r; Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}
Shape s = new Circle(2);   // runtime polymorphism
System.out.println(s.area());
13

Topic 13

Interfaces

javainterface Printable { void print(); }
interface Showable  { default void show() { System.out.println("Showing"); } }

class Report implements Printable, Showable {      // multiple inheritance of type
    public void print() { System.out.println("Printing report"); }
}
ComparisonAbstract class and interface
Abstract class
Interface

Methods

Abstract and concrete

Abstract; default and static methods allowed since Java 8

Variables

Any kind

public static final constants only

Inheritance

A class extends only one

A class implements many

Constructor

Yes

No

Keyword

extends

implements

14

Topic 14

Packages

java// File: mypack/Fees.java
package mypack;
public class Fees {
    public double total(double tuition, double hostel) { return tuition + hostel; }
}

// File: Main.java
import mypack.Fees;            // or import mypack.*;
public class Main {
    public static void main(String[] a) { System.out.println(new Fees().total(42000, 60000)); }
}
  • Compile with javac -d . Fees.java to create the mypack folder. Built-in packages: java.lang (auto-imported), java.util, java.io, java.awt, java.net, java.sql.

Key terms

Constructor
Special method initialising an object
Static member
Belongs to the class, shared by all objects
Overriding
Subclass redefining a superclass method
Abstract class
Class that cannot be instantiated
Interface
Contract of methods a class implements

Quick revision

  • Classes, objects, modifiers, pass-by-value.
  • Constructors, overloading, static, garbage collection.
  • Arrays; String, StringBuilder.
  • Inheritance, overriding, polymorphism, abstract, final, interfaces, packages.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.What is a constructor?
  2. Q2.Is Java pass-by-value or pass-by-reference?
  3. Q3.What is garbage collection?
  4. Q4.Distinguish overloading and overriding.
  5. Q5.Distinguish abstract class and interface.
  6. Q6.What is a package?

Long-answer questions

  1. Q1.Explain constructors and overloading with examples.
  2. Q2.Explain inheritance and polymorphism in Java.
  3. Q3.Explain interfaces and packages.

Stuck on this unit?

Message SBS on WhatsApp for help with Java Technologies, or to ask about studying M.Sc IT at Synetic.

WhatsApp us