Unit 2 of 4 · B.Sc IT Sem 5

Unit 2: Classes, inheritance, arrays and packages

Programming in Java notes · PTU syllabus (BSIT502/BSBC502)

7 min read11 topics10 exam questions
On this page
  1. Unit summary
  2. Defining classes, variables and methods
  3. Creating objects
  4. Constructors
  5. Method overloading
  6. Static members
  7. Inheritance: extending a class
  8. Final variables, methods and classes
  9. Arrays and jagged arrays
  10. Strings and vectors
  11. Interfaces and multiple inheritance
  12. Creating and accessing packages
  13. Key terms
  14. Quick revision
  15. Important questions

Unit summary

Classes are the building blocks of Java programs, and packages organise them. This unit covers defining classes with variables and methods, creating objects, constructors, method overloading, static members, inheritance and overriding, final variables, methods and classes, arrays, jagged arrays, strings and vectors, interfaces and multiple inheritance, and creating and accessing packages.

After this unit you can

  • Define classes, create objects and use constructors
  • Apply overloading, static members, inheritance and overriding
  • Use arrays, strings and vectors
  • Implement interfaces and create packages

PTU syllabus topics

  • Defining classes
  • adding variables and methods
  • creating objects
  • constructors
  • method overloading
  • static members
  • extending a class
  • overriding methods
  • final variables/methods/classes
  • arrays/jagged arrays/strings/vectors
  • defining and implementing interfaces
  • multiple inheritance via interfaces
  • creating and accessing packages
1

Topic 1

Defining classes, variables and methods

A class is a blueprint containing fields (variables) and methods. A constructor has the same name as the class and initialises new 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).

Example

Using a constructor: Student(int r, String n) { roll = r; name = n; } lets you write new Student(1, "Asha"). A method void show() { System.out.println(roll + " " + name); } then prints 1 Asha.

Exam tip

Constructors have no return type, not even void.

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

Example

References, not copies: Student s1 = new Student(); Student s2 = s1; creates one object with two references. Changing s2.name = "Ravi"; also changes s1.name, because both point to the same object.

Exam tip

new creates the object on the heap; the variable only holds a reference.

3

Topic 3

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.

Example

Constructor overloading and `this()`: a class Box has Box() { this(1, 1, 1); } and Box(int l, int b, int h) { … }. new Box() calls the first constructor, which passes 1, 1, 1 to the second, so the default box has volume 1; new Box(2, 3, 4) calls the second directly and has volume 24. A call to this(…) or super(…) must be the first statement in a constructor.

4

Topic 4

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.
ComparisonOverloading vs overriding
Method overloading
Method overriding

Where

In the same class

In a subclass

Signature

Same name, different parameters

Same name and same parameters

Decided at

Compile time (static polymorphism)

Run time (dynamic method dispatch)

Return type

Can differ

Same or a subtype

Example

add(int, int) and add(double, double)

Dog's sound() replaces Animal's sound()

Example

Which method runs? Animal a = new Dog(); a.sound(); prints the Dog version, because overridden methods are chosen at run time by the actual object, not the reference type. But a.fetch() (a method only in Dog) will not compile, because the compiler checks the reference type, Animal.

5

Topic 5

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.

Example

A static counter: class Student { static int count = 0; Student() { count++; } }. After new Student() three times, Student.count is 3 — there is one copy of a static variable shared by all objects, whereas each object has its own copy of an instance variable.

6

Topic 6

Inheritance: extending a class

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

Exam tip

Java classes support single, multilevel and hierarchical inheritance, but not multiple inheritance of classes — a class can extend only one class. Multiple inheritance is achieved by implementing several interfaces: class C extends A implements X, Y.

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

Topic 7

Final variables, methods and 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

Example

final in use: final double PI = 3.14159; cannot be reassigned; a final method in a parent class cannot be overridden by a subclass; the String class is final, so no class can extend it.

Exam tip

final variable = constant; final method = no overriding; final class = no inheritance.

8

Topic 8

Arrays and jagged arrays

A jagged array is a two-dimensional array whose rows have different lengths.

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);

Example

A jagged array: int[][] j = new int[3][]; j[0] = new int[2]; j[1] = new int[4]; j[2] = new int[1]; — row 0 has 2 elements, row 1 has 4 and row 2 has 1. j[1].length returns 4.

Exam tip

Every Java array has a length property; accessing an index outside it throws ArrayIndexOutOfBoundsException.

9

Topic 9

Strings and vectors

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.

Example

`==` vs `equals()` with strings: String a = "SBS"; String b = "SBS"; String c = new String("SBS"); — a == b is true (both refer to the same literal in the string pool), a == c is false (c is a new object), and a.equals(c) is true (same characters). Always compare string contents with equals().

Exam tip

Strings are immutable: s.concat("!") returns a new string and leaves s unchanged unless you write s = s.concat("!");. For many changes in a loop, use StringBuilder.

10

Topic 10

Interfaces and multiple inheritance

Java does not allow a class to extend more than one class, but a class can implement several interfaces — this is how Java achieves multiple inheritance of type.

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

Example

Implementing two interfaces: class Report implements Printable, Showable { public void print() { System.out.println("Printing"); } } — Report must define print() and inherits the default show() method.

Exam tip

Interface methods are public and abstract by default; Java 8 added default and static methods.

11

Topic 11

Creating and accessing packages

A package groups related classes and interfaces, prevents name conflicts and controls access. Built-in packages include java.lang, java.util and java.io.

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.

Example

Using a package: after compiling Fees.java into the folder mypack, another program writes import mypack.Fees; and then new Fees().total(45000, 5000) to use the class.

Exam tip

Folder structure must match the package name; java.lang is imported automatically.

Key terms

Constructor
Special method initialising a new object
Method overloading
Same method name with different parameters
Method overriding
Subclass redefining a superclass method
Interface
Collection of abstract methods and constants
Package
Group of related classes and interfaces

Quick revision

  • Class, object, new, access modifiers.
  • Constructors, this, overloading, static members and blocks.
  • extends, super, overriding, dynamic dispatch; final; abstract classes.
  • Arrays, jagged arrays, String, StringBuilder, Vector.
  • Interfaces, multiple inheritance, packages and import.

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.Distinguish overloading and overriding.
  3. Q3.What is a static variable?
  4. Q4.State three uses of final.
  5. Q5.What is a jagged array?
  6. Q6.How does Java achieve multiple inheritance?

Long-answer questions

  1. Q1.Explain constructors and method overloading with programs.
  2. Q2.Explain inheritance and method overriding in Java.
  3. Q3.Explain arrays, strings and vectors with examples.
  4. Q4.Explain interfaces and packages with programs.

Stuck on this unit?

Message SBS on WhatsApp for help with Programming in Java, or to ask about studying B.Sc IT at Synetic.

WhatsApp us