Unit 2: Classes, inheritance, arrays and packages
Programming in Java notes · PTU syllabus (BSIT502/BSBC502)
On this page
- Unit summary
- Defining classes, variables and methods
- Creating objects
- Constructors
- Method overloading
- Static members
- Inheritance: extending a class
- Final variables, methods and classes
- Arrays and jagged arrays
- Strings and vectors
- Interfaces and multiple inheritance
- Creating and accessing packages
- Key terms
- Quick revision
- 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
Where
Same class
Subclass
Signature
Different parameters
Same parameters
Binding
Compile time
Run time
Purpose
Same name, different inputs
Change inherited behaviour
Topic 1
Defining classes, variables and methods
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).
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 objectTopic 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.
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.
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.
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 runsSingle
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.
Topic 7
Final variables, methods and classes
- 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
Topic 8
Arrays and jagged 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);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.
Topic 10
Interfaces and multiple inheritance
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"); }
}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
Topic 11
Creating and accessing 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 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
- Q1.What is a constructor?
- Q2.Distinguish overloading and overriding.
- Q3.What is a static variable?
- Q4.State three uses of final.
- Q5.What is a jagged array?
- Q6.How does Java achieve multiple inheritance?
Long-answer questions
- Q1.Explain constructors and method overloading with programs.
- Q2.Explain inheritance and method overriding in Java.
- Q3.Explain arrays, strings and vectors with examples.
- 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.
