Docsity

Java OOP Study Guide: Classes, Inheritance, Polymorphism, Interfaces and Exceptions, Study Guides, Projects, Research of Java Programming

Toggle sidebar
bg1
Object-Oriented Programming in Java:
Classes, Inheritance, Polymorphism
and Exceptions
A study guide with runnable code, a summary table and practice questions
Author: Psychedelic Tunes
How to use this guide. Every program in this guide was compiled with javac and run, and the output
shown under each program is its actual output. To try one yourself, save each class in a file named after
the class (for example BankAccount.java ), put the files for one example in the same folder, and run
javac *.java then java Main . The code uses standard Java (version 8 or later).
Contents
The four pillars of OOP
Classes, objects and encapsulation
Inheritance and abstract classes
Polymorphism: overriding and overloading
Interfaces
Exceptions
equals, hashCode and object identity
Summary table
Practice questions and answers
1. The four pillars of OOP
Object-oriented programming (OOP) organises a program around objects: bundles of data (fields)
and behaviour (methods). A class is the blueprint; an object is one instance built from it.
Pillar Idea in one line Java tools
Encapsulation Hide an object's data and allow access only through
its methods
private fields, getters/setters,
validation inside methods
Abstraction Show what an object does, hide how it does it abstract classes, interface
Inheritance A new class reuses and extends an existing class ("is-
a")
extends , super
Polymorphism One interface, many forms: the same call behaves
differently depending on the object
Method overriding, overloading,
parent-type references
Access modifiers control visibility:
Modifier Same class Same package Subclass (other package) Everywhere
private Yes No No No
(none: package-private) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
2. Classes, objects and encapsulation
The BankAccount class keeps its balance private , so the only way to change it is through deposit and
withdraw , which check the amount first. It also shows constructors, constructor overloading with
this(...) , a final field, a static field shared by all objects, and an overridden toString .
1.
2.
3.
4.
5.
6.
7.
8.
9.
Psychedelic Tunes Page 1 of 12
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Java OOP Study Guide: Classes, Inheritance, Polymorphism, Interfaces and Exceptions and more Study Guides, Projects, Research Java Programming in PDF only on Docsity!

Object-Oriented Programming in Java:

Classes, Inheritance, Polymorphism

and Exceptions

A study guide with runnable code, a summary table and practice questions

Author: Psychedelic Tunes

How to use this guide. Every program in this guide was compiled with javac and run, and the output shown under each program is its actual output. To try one yourself, save each class in a file named after the class (for example BankAccount.java ), put the files for one example in the same folder, and run javac *.java then java Main. The code uses standard Java (version 8 or later).

Contents

The four pillars of OOP Classes, objects and encapsulation Inheritance and abstract classes Polymorphism: overriding and overloading Interfaces Exceptions equals, hashCode and object identity Summary table Practice questions and answers

1. The four pillars of OOP

Object-oriented programming (OOP) organises a program around objects : bundles of data (fields) and behaviour (methods). A class is the blueprint; an object is one instance built from it.

Pillar Idea in one line Java tools Encapsulation Hide an object's data and allow access only through its methods

private fields, getters/setters, validation inside methods Abstraction Show what an object does, hide how it does it abstract classes, interface Inheritance A new class reuses and extends an existing class ("is- a")

extends , super

Polymorphism One interface, many forms: the same call behaves differently depending on the object

Method overriding, overloading, parent-type references

Access modifiers control visibility:

Modifier Same class Same package Subclass (other package) Everywhere private Yes^ No^ No^ No (none: package-private) Yes Yes No No protected Yes^ Yes^ Yes^ No public Yes^ Yes^ Yes^ Yes

2. Classes, objects and encapsulation

The BankAccount class keeps its balance private , so the only way to change it is through deposit and withdraw , which check the amount first. It also shows constructors, constructor overloading with this(...) , a final field, a static field shared by all objects, and an overridden toString.

public class BankAccount { private static int accountsOpened = 0; // shared by all objects

private final String accountNo; // set once, never changed private String owner; private double balance;

public BankAccount(String owner, double openingBalance) { this.owner = owner; this.balance = openingBalance; accountsOpened++; this.accountNo = "AC" + (1000 + accountsOpened); }

public BankAccount(String owner) { // overloaded constructor this(owner, 0.0); }

public void deposit(double amount) { if (amount <= 0) { throw new IllegalArgumentException("Deposit must be positive"); } balance += amount; }

public boolean withdraw(double amount) { if (amount <= 0 || amount > balance) { return false; } balance -= amount; return true; }

public double getBalance() { return balance; } public String getAccountNo() { return accountNo; } public static int getAccountsOpened() { return accountsOpened; }

@Override public String toString() { return accountNo + " (" + owner + "): " + String.format("%.2f", balance); } }

public class Main { public static void main(String[] args) { BankAccount a = new BankAccount("Amina", 5000); BankAccount b = new BankAccount("Brian");

a.deposit(1500); boolean ok1 = a.withdraw(2000); boolean ok2 = b.withdraw(100); // b has 0, so this fails

System.out.println(a); System.out.println(b); System.out.println("Withdrawals: " + ok1 + ", " + ok2); System.out.println("Accounts opened: " + BankAccount.getAccountsOpened()); // a.balance = 1000000; // compile error: balance has private access } }

Output

this.width = width; this.height = height; }

@Override public double area() { return width * height; } }

public class Square extends Rectangle { public Square(double side) { super("Square", side, side); }

@Override public String describe() { // overrides and extends the parent version return super.describe() + " (side " + width + ")"; } }

Key rules

A subclass constructor must call a superclass constructor, with super(...) as its first statement. If you do not write one, Java inserts super() automatically, which fails to compile if the parent has no no-argument constructor. Constructors run from parent to child : the Shape part of a Square is built first, then Rectangle , then Square. super.describe() calls the parent's version of an overridden method. protected fields ( width , height ) are visible to subclasses. A final class cannot be extended (for example String ); a final method cannot be overridden.

4. Polymorphism: overriding and overloading

public class Main { // Overloading: same name, different parameter lists (decided at compile time) static double total(Shape s) { return s.area(); } static double total(Shape s1, Shape s2) { return s1.area() + s2.area(); }

public static void main(String[] args) { Shape[] shapes = { new Circle(1.5), new Rectangle(4, 2.5), new Square(3) };

for (Shape s : shapes) { System.out.println(s.describe()); // overriding: decided at run time }

System.out.printf("Total of first two: %.2f%n", total(shapes[0], shapes[1]));

Shape s = shapes[2]; System.out.println(s instanceof Rectangle); // a Square IS-A Rectangle if (s instanceof Square) { Square sq = (Square) s; // downcast after checking System.out.println("Downcast OK: " + sq.getName()); } // Shape x = new Shape("x"); // compile error: Shape is abstract } }

Output

Circle with area 7. Rectangle with area 10. Square with area 9.00 (side 3.0) Total of first two: 17.

true Downcast OK: Square

Check: circle area = Ļ€ Ɨ 1.5² = 7.0686 → 7.07; rectangle = 4 Ɨ 2.5 = 10; square = 3 Ɨ 3 = 9; 7.07 + 10.00 = 17.07.

Overriding (run-time polymorphism) Overloading (compile-time polymorphism) Where Subclass redefines a method inherited from its parent

Same class has several methods with the same name Signature Same name and same parameter list Same name, different parameter list (number, type or order) Return type Same, or a subtype (covariant return) Can differ, but return type alone cannot distinguish overloads Decided At run time , by the actual object type (dynamic binding)

At compile time , by the argument types

Example above

area() and describe() total(Shape) and total(Shape, Shape)

Upcasting and downcasting. Assigning a Square to a Shape variable is an automatic, safe upcast. Going back ( (Square) s ) is a downcast ; it compiles but throws ClassCastException at run time if the object is not really a Square , so check with instanceof first. The variable's declared type decides which methods you may call ; the object's actual type decides which version runs.

Static methods are not overridden. A static method with the same signature in a subclass hides the parent's method, and the call is chosen by the declared type (see practice question 6).

5. Interfaces

An interface defines a contract: a set of methods that implementing classes promise to provide. A class can implement many interfaces , which is how Java supports multiple inheritance of type.

public interface Payable { double TAX_RATE = 0.16; // implicitly public static final

double amountDue(); // implicitly public abstract

default double amountWithTax() { // default method (Java 8+) return amountDue() * (1 + TAX_RATE); } }

public interface Printable { String toPrintLine(); }

public class Invoice implements Payable, Printable { // a class can implement many interfaces private final String item; private final int quantity; private final double unitPrice;

public Invoice(String item, int quantity, double unitPrice) { this.item = item; this.quantity = quantity; this.unitPrice = unitPrice; }

@Override public double amountDue() { return quantity * unitPrice; }

@Override public String toPrintLine() {

Abstract class Interface Fields Any (instance or static, any access)

Only public static final constants

Constructors Yes No Methods Abstract and concrete Abstract, plus default and static (Java 8+) and private helpers (Java 9+) Use when Related classes share code and state ("is-a")

Unrelated classes share a capability ("can-do"), such as Comparable , Runnable , Payable

Payable::amountDue is a method reference , a short form of the lambda p -> p.amountDue() , used here to tell the sort which value to compare.

6. Exceptions

An exception is an object that signals an error or unusual condition. When one is thrown , normal execution stops and Java searches back up the call stack for a matching catch block.

The hierarchy (simplified):

Throwable ā”œā”€ā”€ Error serious JVM problems (OutOfMemoryError) - do not catch └── Exception CHECKED: must be caught or declared with 'throws' │ IOException, SQLException, user-defined subclasses of Exception └── RuntimeException UNCHECKED: compiler does not force handling NullPointerException, ArithmeticException, IllegalArgumentException, ArrayIndexOutOfBoundsException, NumberFormatException, ClassCastException

Example: a custom checked exception, multiple catch blocks, finally and try-with-resources.

public class InsufficientFundsException extends Exception { // checked exception private static final long serialVersionUID = 1L; private final double shortfall;

public InsufficientFundsException(String message, double shortfall) { super(message); this.shortfall = shortfall; }

public double getShortfall() { return shortfall; } }

public class Wallet { private double balance;

public Wallet(double balance) { this.balance = balance; }

public void pay(double amount) throws InsufficientFundsException { if (amount <= 0) { // IllegalArgumentException is unchecked throw new IllegalArgumentException("Amount must be positive: " + amount); } if (amount > balance) { throw new InsufficientFundsException("Not enough funds", amount - balance); } balance -= amount; }

public double getBalance() { return balance; } }

import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader;

public class Main { public static void main(String[] args) { Wallet w = new Wallet(1000); double[] payments = { 400, 700, -50 };

for (double amt : payments) { try { w.pay(amt); System.out.println("Paid " + amt + ", balance " + w.getBalance()); } catch (InsufficientFundsException e) { System.out.println(e.getMessage() + ", short by " + e.getShortfall()); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } finally { System.out.println("-- attempt for " + amt + " finished"); } }

// Parsing user input safely String[] inputs = { "42", "4x2" }; for (String in : inputs) { try { int n = Integer.parseInt(in); System.out.println("Parsed " + n); } catch (NumberFormatException e) { System.out.println("Not a number: " + in); } }

// try-with-resources closes the reader automatically try (BufferedReader r = new BufferedReader(new StringReader("line one\nline two"))) { System.out.println("First line: " + r.readLine()); } catch (IOException e) { System.out.println("Read failed: " + e.getMessage()); } } }

Output

Paid 400.0, balance 600. -- attempt for 400.0 finished Not enough funds, short by 100. -- attempt for 700.0 finished Rejected: Amount must be positive: -50. -- attempt for -50.0 finished Parsed 42 Not a number: 4x First line: line one

Rules to remember

throw creates and raises an exception; throws in a method header declares that the method may pass a checked exception to its caller. A checked exception (subclass of Exception but not of RuntimeException ) must be caught or declared, or the code will not compile. Unchecked exceptions need not be. Order catch blocks from most specific to most general. Putting catch (Exception e) before catch (IOException e) is a compile error because the second block can never run.

8. Summary table

Concept Key point Keyword / example Class vs object Blueprint vs instance (^) new BankAccount("Amina", 5000) Encapsulation Private data, public methods with validation private double balance; Constructor Same name as class, no return type; can be overloaded

this(...) , super(...)

static Belongs to the class, shared by all objects BankAccount.getAccountsOpened() final Variable: assign once; method: cannot override; class: cannot extend

final String accountNo

Inheritance Single class inheritance, "is-a" class Square extends Rectangle Abstract class Cannot instantiate; may have abstract and concrete methods

abstract double area();

Interface Contract; a class can implement many implements Payable, Printable Overriding Same signature in subclass; chosen at run time @Override double area() Overloading Same name, different parameters; chosen at compile time

total(Shape) / total(Shape, Shape) Upcast / downcast

Child → parent is automatic; parent → child needs a cast and instanceof check

(Square) s

Checked exception

Must catch or declare throws InsufficientFundsException Unchecked exception

RuntimeException and subclasses IllegalArgumentException

finally Always runs clean-up code try-with- resources

Auto-closes AutoCloseable resources try (BufferedReader r = ...)

== vs equals Reference vs content; override hashCode with equals

a.equals(b)

9. Practice questions

Name the four pillars of OOP and give a one-line definition of each. What is the difference between a class and an object? Why should fields usually be private? Use the BankAccount example. What is wrong with this code? class Animal { Animal(String n) { } } class Dog extends Animal { Dog() { } } What does this print? A x = new B(); x.show(); where class A { void show() { System.out.println("A"); } } and class B extends A { void show() { System.out.println("B"); } } What does this print, and why? P p = new C(); System.out.println(p.id()); where P has static String id() { return "P"; } and C extends P has static String id() { return "C"; }. What does new Derived(); print, if Base() { System.out.print("Base "); } and Derived extends Base has Derived() { System.out.println("Derived"); }? Give two differences between method overloading and method overriding. Can you write Shape s = new Shape("x"); for the abstract Shape class in Section 3? Explain. Give three differences between an abstract class and an interface. Can an interface have a method with a body? Explain with the Payable example. Write a class Book that implements Comparable so books sort by price. What is the difference between a checked and an unchecked exception? Give an example of each. What does this method return, and what does it print? static int f() { try { return 1; } finally { System.out.println("finally"); } } What is printed by int[] arr = new int[3]; arr[3] = 10; inside try { ... System.out.println("stored"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Caught: " + e.getClass().getSimpleName()); }? Why does the following fail to compile? try { ... } catch (Exception e) { ... } catch (IOException e) { ... } Explain the difference between throw and throws. What is the benefit of try-with-resources over closing a file in finally? Why must hashCode be overridden when equals is overridden? What happens at run time with Shape s = new Circle(2); Square q = (Square) s;? How do you prevent it?

Answers

1. Encapsulation: bundle data with methods and hide the data. Abstraction: expose what an object does, hide how. Inheritance: a class reuses and extends another class. Polymorphism: the same method call behaves differently for different object types. 2. A class is a template that defines fields and methods; an object is a concrete instance created from it with new , with its own values for the fields. One class can produce many objects. 3. Private fields can only be changed through methods that enforce rules. In BankAccount , withdraw refuses amounts larger than the balance; if balance were public, any code could set it to a negative or invented value. Private fields also let you change the internal design without breaking other code. 4. Dog() implicitly calls super() , but Animal has no no-argument constructor, so it does not compile. Fix: Dog() { super("Dog"); } , or add Animal() { }. 5. B. The method is overridden, and the version that runs is chosen by the actual object ( B ), not by the variable type ( A ). 6. P. Static methods are not overridden; C.id() only hides P.id(). Static calls are bound at compile time using the declared type P. (Calling static methods through an instance is legal but bad style; prefer P.id() .) 7. Base Derived. The parent constructor always runs first.