UNIV LOGO D E P A R T M E N T O F C O M P U T E R S C I E N C E & E N G I N E E R I N G Object - Oriented Programming Concepts, Enumerations, Autoboxing and Annotations in Java A University - Level Course on OOP Principles, the Java Type System & the Collections Framework C O U R S E Programming in Java F A C U L T Y Course Instructor D E P A R T M E N T Computer Science & Engineering D U R A T I O N 10 Hours / 40 Slides Suitable for classroom teaching, laboratory demonstration, assignments & technical interview preparation. Course Learning Outcomes What you will be able to do by the end of this module OVERVIEW Java OOP, Enums, Autoboxing & Annotations Slide 2 / 40 1 Understand OOP Explain procedural vs. object - oriented paradigms and the four pillars. 2 Design Classes & Objects Model real entities as classes with state, behaviour and constructors. 3 Inheritance & Polymorphism Reuse and extend behaviour; bind methods dynamically at runtime. 4 Use Enums & Annotations Model fixed sets and add metadata that tools and compilers read. 5 Master Autoboxing Bridge primitives and wrapper objects safely and efficiently. 6 Use Collections Framework Choose List, Set, Queue or Map for the right data structure. Course Roadmap Fundamentals Abstraction Encapsulation Inheritance Polymorphism Enums Autoboxing Annotations Collections Introduction to Object - Oriented Programming MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 3 / 40 LEARNING OBJECTIVES Contrast procedural vs. OOP Identify the need for OOP List the characteristics of OOP Procedural Programming • Program = sequence of functions/procedures • Data and functions are kept separate • Top - down design; global data is exposed • Hard to scale and maintain as code grows • Examples: C, Pascal, BASIC, FORTRAN Object - Oriented Programming • Program = collaborating objects (data + behaviour) • Data is encapsulated inside objects • Bottom - up design; access is controlled • Scales well; promotes reuse and modelling of reality • Examples: Java, C++, C#, Python WHY OOP? Large systems map naturally to real - world objects (Student, Account, Order). OOP manages complexity through encapsulation, reuse via inheritance, and flexibility via polymorphism. Characteristics of OOP • Class · Object · Abstraction · Encapsulation · Inheritance · Polymorphism · Message Passing Benefits of Object - Oriented Programming MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 4 / 40 LEARNING OBJECTIVES Explain the five core benefits of OOP Connect each benefit to industry practice 01 Reusability Inherit and compose existing classes instead of rewriting code. 02 Modularity Independent objects can be developed, tested and replaced separately. 03 Maintainability Localised changes; well - defined interfaces reduce ripple effects. 04 Scalability New features added by extending classes, not rewriting them. 05 Security Encapsulation hides data; access modifiers protect internal state. INDUSTRY APPLICATIONS Banking systems model Accounts and Transactions; e - commerce platforms reuse Product and Order hierarchies; hospital software ext ends a common Person base for Patient, Doctor and Staff. OOP's modularity is why large teams can build these systems in parallel. Java Variables and Data Types MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 5 / 40 LEARNING OBJECTIVES Distinguish primitive vs. non - primitive types Recall sizes and default values Type Size Default Range / Notes byte 1 byte 0 - 128 to 127 short 2 bytes 0 - 32,768 to 32,767 int 4 bytes 0 approx. +/ - 2.1 billion long 8 bytes 0L very large integers float 4 bytes 0.0f single - precision decimal double 8 bytes 0.0d double - precision decimal char 2 bytes ' \ u0000' single Unicode character boolean 1 bit* false true or false * JVM - dependent size Non - Primitive (Reference) Types • Classes, Interfaces, Arrays, Strings, Enums • Store references (addresses), not raw values • Default value is null; created with new Variable declaration syntax int age = 21 ; // primitive double gpa = 8.75 ; char grade = 'A' ; boolean pass = true ; String name = "Asha" ; // reference type int [] marks = { 90 , 85 , 78 }; Java Variables — Worked Example MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 6 / 40 LEARNING OBJECTIVES Trace declaration, initialisation and output Visualise stack vs. heap storage VariablesDemo.java public class VariablesDemo { public static void main( String [] args) { int rollNo = 101 ; // stack double marks = 92.5 ; // stack char section = 'B' ; // stack String name = "Ravi" ; // ref - > heap boolean isPass = marks >= 40 ; System .out.println(name + " (" + rollNo + ")" ); System .out.println( "Marks : " + marks); System .out.println( "Pass : " + isPass); } } Memory Representation STACK rollNo = 101 marks = 92.5 section = 'B' name = ref ─── ► HEAP "Ravi" String object OUTPUT Ravi (101) Marks : 92.5 Pass : true Classes and Objects MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 7 / 40 LEARNING OBJECTIVES Define class and object Relate the blueprint analogy Read a UML class diagram Definitions • Class: a blueprint/template defining state + behaviour • Object: a concrete instance of a class in memory • One class → many independent objects (each with its own data) REAL - WORLD ANALOGY Class 'Car' is the design; each car you drive is an object. 'Student', 'BankAccount' work the same way — one definition, many instances each holding their own values. UML Class Diagram Student - rollNo : int - name : String - gpa : double + enroll() : void + getGpa() : double + display() : void ─ private + public Creating Classes and Objects MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 8 / 40 LEARNING OBJECTIVES Declare a class with fields, constructor & methods Instantiate objects with new Student.java class Student { int rollNo; String name; Student( int r, String n) { // constructor rollNo = r; name = n; } void display() { System .out.println(rollNo + " - " + name); } } public class Demo { public static void main( String [] a) { Student s1 = new Student( 101 , "Asha" ); s1.display(); // 101 - Asha } } Heap Memory on new s1 ref Student object rollNo = 101 name = "Asha" STEPS 1. new allocates heap memory 2. Constructor runs to initialise fields 3. Reference s1 stored on the stack Object Lifecycle MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 9 / 40 LEARNING OBJECTIVES Order the five lifecycle stages Explain garbage collection Declaration Student s; Instantiation new keyword Initialization constructor runs Usage call methods Garbage Collection no references left Student s; // 1 declaration s = new Student( 101 , "A" ); // 2 + 3 instantiate+init s.display(); // 4 usage s = null ; // eligible for GC System .gc(); // 5 request collection GARBAGE COLLECTION Java reclaims memory automatically. An object becomes eligible when no live reference points to it. The JVM (not you) decides when to run GC; finalize()/Cleaner may run beforehand. Constructors MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 10 / 40 LEARNING OBJECTIVES State the purpose & rules of constructors List the types of constructors Purpose & Features • Special method that initialises a new object • Same name as the class; no return type (not even void) • Invoked automatically when new is used • Can be overloaded to allow different ways to create objects Constructor Rules • If you write none, Java provides a default no - arg constructor • Writing any constructor removes the implicit default • this(...) chains constructors; super(...) calls the parent Types of Constructors Default No parameters; sets default values. No - argument Explicitly written, takes no parameters. Parameterized Accepts arguments to set initial state. Copy (concept) Builds an object from another object's state. Constructor Examples MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 11 / 40 LEARNING OBJECTIVES Write default, parameterized and copy constructors Predict their output Box.java class Box { int w, h; Box() { // default / no - arg w = 1 ; h = 1 ; } Box( int w, int h) { // parameterized this .w = w; this .h = h; } Box(Box b) { // copy constructor this .w = b.w; this .h = b.h; } int area() { return w * h; } } // usage Box a = new Box( 4 , 3 ); // 12 Box b = new Box(a); // copy - > 12 Box c = new Box(); // 1 OUTPUT a.area() = 12 b.area() = 12 (copied) c.area() = 1 (default) Key Points • this distinguishes field from parameter • Copy constructor duplicates state, not reference • Overloading = same name, different parameter lists • Constructor chaining avoids duplicate init code Method Overloading MODULE 1 · FUNDAMENTALS Java OOP, Enums, Autoboxing & Annotations Slide 12 / 40 LEARNING OBJECTIVES Define compile - time polymorphism Apply the overloading rules Calculator.java class Calculator { 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; } } Calculator c = new Calculator(); c.add( 2 , 3 ); // - > int version c.add( 2.5 , 3.5 ); // - > double version c.add( 1 , 2 , 3 ); // - > three - arg version Rules • Same method name, different parameter list • Differ by number, type or order of parameters • Return type alone is NOT enough to overload • Resolved by the compiler (static binding) COMPILE - TIME POLYMORPHISM The correct method is chosen at compile time from the argument types — also called static or early binding. INTERVIEW / VIVA Q: Can methods be overloaded by return type only? A: No. Q: Is main() overloadable? A: Yes, but JVM calls String[] version. Q: Overloading vs overriding? A: Compile - time vs runtime. Abstraction MODULE 2 · ABSTRACTION Java OOP, Enums, Autoboxing & Annotations Slide 13 / 40 LEARNING OBJECTIVES Define abstraction & its need Separate 'what' from 'how' Definition & Need • Hiding implementation detail; exposing only essentials • Reduces complexity — users see 'what', not 'how' • Achieved via abstract classes and interfaces Benefits • Simplifies the programming model • Decouples interface from implementation • Enables independent change of internals REAL - WORLD: ATM You press 'Withdraw' and get cash. The internal authentication, balance check and dispensing logic stay hidden. The ATM exposes a simple abstract interface over complex machinery. REAL - WORLD: VEHICLE A driver uses accelerator, brake and steering. The engine, transmission and fuel - injection details are abstracted away. Case study: Vehicle Reservation System exposes book()/return() over hidden fleet logic. Abstract Classes MODULE 2 · ABSTRACTION Java OOP, Enums, Autoboxing & Annotations Slide 14 / 40 LEARNING OBJECTIVES Declare abstract classes & methods Know when a subclass must override Shape.java abstract class Shape { abstract double area(); // no body void describe() { // concrete method System .out.println( "Area = " + area()); } } class Circle extends Shape { double r; Circle( double r) { this .r = r; } double area() { return Math .PI * r * r; } } // Shape s = new Shape(); // ERROR: cannot instantiate Shape s = new Circle( 2 ); s.describe(); // Area = 12.566... Features • Declared with the abstract keyword • May mix abstract and concrete methods • Cannot be instantiated directly • Subclass must override all abstract methods • Can have constructors, fields & static members VIVA Q: Can an abstract class have a constructor? A: Yes. Q: Abstract class without abstract methods? A: Allowed. Q: Can it be final? A: No — contradictory. Interfaces in Java MODULE 2 · ABSTRACTION Java OOP, Enums, Autoboxing & Annotations Slide 15 / 40 LEARNING OBJECTIVES Define an interface & its features Compare interface vs. abstract class Features • Pure contract: method signatures, no state • Members are public; fields are public static final • A class may implement many interfaces • Java 8+: default and static methods allowed UML — Interface Realization Drawable «abstract» «interface» + draw() imp lement s Circle - r : double + draw() Aspect Abstract Class Interface Keyword abstract class interface Multiple inheritance No Yes Fields Any kind public static final Methods Abstract + concrete Abstract + default/static Constructor Yes No Use when Shared base + state Pure capability contract Interface Implementation Example MODULE 2 · ABSTRACTION Java OOP, Enums, Autoboxing & Annotations Slide 16 / 40 LEARNING OBJECTIVES Implement multiple interfaces Apply interfaces to real systems Payroll.java interface Payable { double pay(); } interface Taxable { double tax(); } class Employee implements Payable, Taxable { double salary; Employee( double s) { salary = s; } public double pay() { return salary; } public double tax() { return salary * 0.1 ; } } Employee e = new Employee( 50000 ); System .out.println(e.pay()); // 50000.0 System .out.println(e.tax()); // 5000.0 Multiple Implementation • One class realises many contracts • Each interface adds a capability • Achieves multiple inheritance of type PRACTICAL USES Comparable for sorting Runnable for threads Library system: Borrowable, Reservable contracts MODULE 2 VIVA When to choose interface over abstract class? · Can an interface extend another interface? (Yes) · What is a marker inter fac e? Encapsulation MODULE 3 · ENCAPSULATION Java OOP, Enums, Autoboxing & Annotations Slide 17 / 40 LEARNING OBJECTIVES Apply data hiding with access modifiers Use getters & setters correctly Data Hiding • Bundle data + methods in one class • Make fields private; expose controlled methods • Validate input inside setters Modifier Class Package Subclass World private Yes — — — default Yes Yes — — protected Yes Yes Yes — public Yes Yes Yes Yes class Account { private double balance; // hidden public double getBalance() { // getter return balance; } public void setBalance( double b){ // setter if (b >= 0 ) balance = b; // validation } } BENEFITS Protects object state from invalid values Read - only / write - only fields become possible Internal representation can change freely Improves testability and security Encapsulation — Bank Account (Case Study) MODULE 3 · ENCAPSULATION Java OOP, Enums, Autoboxing & Annotations Slide 18 / 40 LEARNING OBJECTIVES Build a safe BankAccount class See security advantages in action BankAccount.java class BankAccount { private long accNo; private double balance; BankAccount( long no, double bal) { accNo = no; balance = bal; } public void deposit( double amt) { if (amt > 0 ) balance += amt; } public boolean withdraw( double amt) { if (amt > 0 && amt <= balance) { balance - = amt; return true ; } return false ; // insufficient funds } public double getBalance() { return balance; } } SECURITY ADVANTAGES balance cannot be set to a negative value No external code can corrupt the field Every change passes through validation Code Explanation • Fields are private — invisible outside • deposit/withdraw guard every change • withdraw returns false on overdraft • Real banks layer auth & audit on top Inheritance Fundamentals MODULE 4 · INHERITANCE Java OOP, Enums, Autoboxing & Annotations Slide 19 / 40 LEARNING OBJECTIVES Define inheritance & the IS - A relation Use extends and super Definition & Benefits • Child class acquires fields/methods of a parent • Promotes code reuse and a natural hierarchy • Keyword extends; super accesses the parent • Models the IS - A relationship IS - A RELATIONSHIP A Car IS - A Vehicle. A SavingsAccount IS - A Account. A Manager IS - A Employee. If 'IS - A' reads naturally, inheritance fits. Parent → Child Vehicle - speed : int + start() : void extends Car - doors : int + honk() : void Types of Inheritance MODULE 4 · INHERITANCE Java OOP, Enums, Autoboxing & Annotations Slide 20 / 40 LEARNING OBJECTIVES Recognise the four inheritance forms in Java Know why multiple (class) inheritance is barred Single A B Multilevel A B C Hierarchical A B C Multiple (interfaces) I1 I2 C WHY NO MULTIPLE CLASS INHERITANCE? Two parents with the same method create ambiguity (the 'diamond problem'). Java avoids it for classes but allows multiple interfaces, where the implementing class resolves the conflict. class A { } class B extends A { } // single class C extends B { } // multilevel class D implements I1, I2 { } // multiple