Introduction to Object-Oriented Programming (OOP) PDF
Document Details
Uploaded by WellBalancedIodine
Tags
Related
- Topic 1.6 Running Program with Objects PDF
- CS0070 Object-Oriented Programming Module 1 PDF
- Object Oriented Programming (2nd Year 1st Sem) PDF
- Introduction to Java Programming and Data Structures (2019) by Y. Daniel Liang - PDF
- VILLASAN Object-Oriented Programming PDF
- Introduction To Object Oriented Programming PDF
Summary
This document provides an introduction to object-oriented programming (OOP) concepts in Java. It covers topics such as procedure-oriented programming, console programming, swing programming, and object-oriented programming paradigms. The document also discusses key differences among these concepts, such as organization, reusability, and maintainability.
Full Transcript
INTRODUCTION TO OBJECT- ORIENTED PROGRAMMING (OOP) Procedure-Oriented Programming ▪ Procedure-oriented programming (POP), also known as structured programming, is a programming paradigm that focuses on organizing a program into a set of functions or procedures. ▪ In this paradigm, the progr...
INTRODUCTION TO OBJECT- ORIENTED PROGRAMMING (OOP) Procedure-Oriented Programming ▪ Procedure-oriented programming (POP), also known as structured programming, is a programming paradigm that focuses on organizing a program into a set of functions or procedures. ▪ In this paradigm, the program is designed as a sequence of procedures, each of which performs a specific task. Console Programming ▪ Is a java programming method that uses ‘text-only’ interfaces Swing Programming ▪ Allows the developers to create graphical user interface Object Oriented Programming ▪ Object-oriented programming (OOP) is a programming paradigm or methodology that uses objects as the fundamental building blocks of software development. ▪ Objects can represent real-world entities with attributes (data) and behavior (functions or methods). Key Differences Organization Procedural: Data and functions are separate. Functions operate on global or passed data. OOP: Data (attributes) and functions (Methods) are encapsulated within objects. Key Differences Reusability Procedural :Functions can be reused, but managing related data requires more manual effort. OOP: Objects can be reused and extended. You can create new classes based on existing ones (inheritance). Key Differences Maintainability Procedural: As the program grows, managing and understanding the flow of data and functions can become complex. OOP: Encapsulation and modularity make the code easier to maintain, as changes to a class are localized. KEY CONCEPTS OF OOP ▪ ENCAPSULATION – Bundling attributes and methods that operate on the data within one unit. ▪ INHERITANCE - The mechanism by which one class can inherit the properties and behaviors of another class. ▪ POLYMORPHISM - Ability of different objects to respond to the same function or method call in different ways. ▪ ABSTRACTION – Hiding complex implementation details and showing only the necessary features of an object. ▪ MODULARITY – allows to code and understand just a particular part of the system without the need to understand the whole system ▪ REUSABILITY – gives the flexibility to use certain programs repeatedly ▪ CONSTRUCTOR - A constructor is a special method in a class used to initialize the object's attributes when an object is created. Classes ▪ A class is a blueprint or template for creating objects. ▪ A foundation from which individual objects are created. ▪ It defines the structure (attributes or properties) and behavior (methods or functions) that its objects will have. ▪ Objects of the same class share the same structure and behavior. ▪ Super Class – base class, ancestor class, parent class ▪ Sub Class – derived class, descendant class, child class ▪ Non-static Class – class that should be instantiated ▪ Static Class – doesn’t require instantiation Object ▪ an instance of class. It has attributes and behaviors. ▪ Each object can have unique values for its attributes, even if they are created from the same class. Attributes ▪ Attributes (also known as fields or properties) are variables within a class that represent the state or characteristics of objects created from that class. They store data that can be manipulated by methods. State ▪ The current values of an object's attributes at any given time.The state can change over time as the object interacts with methods or other objects. Example: ▪ Class – Car ▪ Methods – start(), stop(), accelerate() ▪ Object – myCar ▪ Attributes – color = “red”, engineState = “off” ▪ State of myCar changes when the start() method is invoked, changing engineState to “on” Method ▪ an action done by an object ▪ Methods are functions defined within a class that specify the behavior of objects of that class. They perform actions and manipulate data within the objects. Abstract Method – is an empty method Interfaces ▪ A collection of methods that indicate that a class has some behavior in addition to what it inherits from its superclasses. ▪ Interfaces are used to define a common set of methods that various classes can implement according to their specific needs. Types of Method Instance Method – Operate on an instance of the class (an object). Static Method - Belong to the class rather than any object instance; they don't modify object attributes and can be called on the class itself. Packages ▪ A way of grouping related classes and interfaces in a structured way. ▪ Enabled groups of classes to be available only if they are needed. ▪ Eliminate potential conflicts among class names in different groups of classes. Few things to know… ▪ The class libraries in Java are contained in a package called java. ▪ By default, your Java classes have access only to the classes in java.lang (basic language features). To use classes from any other package, you have to refer to them explicitly by package name or import them on your source file Few things to know… ▪ To refer to a class within a package, you must normally use the full package name. For example, because the Color class is contained in the java.awt package, you refer to it in your programs with notation java.awt.Color Programming Basics Classes, Interface, Packages import java.io.BufferedReader java.io java.lang java.util import java.util.Scanner javax.swing import javax.swing.Frame Way of grouping related classes Instantiation ▪ a process of creating object of the class Ex. Instantiate an object named ‘objectAko’ from class ‘MyClass’ (assuming that MyClass requires no arguments or parameters) MyClass objectAko = new MyClass ( ); Scanner Class ▪ Scanner class is used to read the user’s input from the java.util package. ▪ Declare an input Scanner in the main method to be able to use the methods included to the Scanner class. ▪ Syntax: Scanner scan = new Scanner (System.in); Scanner Class Methods Description ▪ nextLine() ▪ String ▪ nextInt() ▪ Scans the next token of the input as an int. ▪ nextDouble() ▪ Scans the next token of the input as a double. ▪ nextFloat() ▪ Scans the next token of the input as a float. Scanner Class Methods Description ▪ nextBoolean() ▪ Scans the next token of the input into a boolean value and returns that value ▪ nextByte() ▪ Scan the input as a byte ▪ Scans the next token of ▪ nextLong() the input as a long int. ▪ Scans the next token of ▪ nextShort() the input as a short int. BufferedReader Class ▪ Also used to read the user’s input from the java.io package. ▪ Syntax: BufferedReader read = new BufferedReader (new InputStreamReader(System.in)); BufferedReader Class Methods Description ▪ read() ▪ Reads a single character ▪ readLine() ▪ Reads a line of text. Comments in Java ▪ Single Line – use double slash // ? Ex. // defines a class named HelloWorld ▪ Multi-Line – use ? Ex. public class SampleNo1 // defines a class named SampleNo1 { public static void main (String [ ] args) { System.out.println (“ Java is fun! “); System.out.print (“ Let’s enjoy learning it!”); } // end of main } // end of class public static void main (String [ ] args) ▪ This is called the 'main method' and is the entry point to your program for the JVM. public means any other method in the code can access it (as opposed to a private method) static means the Java VM will automatically execute the method void means that it will not return anything (since functions / method are usually expected to return a value.) main is the name of the method. (String args) means that the arguments of the method named main should be strings. In the Java programming language, every application must contain a main method whose signature is: public static void main(String[ ] args) ▪ The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. ▪ The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program. ▪ The main method accepts a single argument: an array of elements of type String. We can use both String[ ] args or String args[]. The Java compiler would accept both forms. You can name the argument anything you want, but most programmers choose "args" or "argv". System.out.println (“ Java is fun ”); System is a class made available by Java to let you manipulate various operating system related objects. It's part of java.lang namespace. out, being one of those objects, is a static publicly available object inside that class. The object itself, representing standard output, is an instance of java.io.PrintStream class. print ( ) is a method of java.io.PrintStream class that lets you output some text into the stream println( ) method, gets you to the new line after the text. System.out.println (“ Java is fun ”); System.out is an object used for sending output to the screen; print is the method that this object carries out in order to send what it is in the parenthesis to the screen. The item or items inside the parenthesis are called arguments and provide the information the method needs to carry out its action. You don't need to import java.io.* because System is part of available to all Java calls package java.lang. Even though out is an instance of java.io.PrintStream, it is still declared *inside* the System class and therefore, you do not need to import java.io. Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 DESIGNING METHODS Parts of a Method Declaration A method declaration specifies all the information needed to call a method. Example of a method declaration: public final void nap(int minutes) throws Exception { //statements } The parts of a method declaration are as follows: Value in Element Required? nap() example Access modifier public No Optional specifier final No Return type void Yes Method name nap Yes Parameter list (int minutes) Yes, but can be empty ( ) Optional exception list throws Exception No { Method body //statements Yes, but can be empty { } } To call the nap() method, just type its name followed by a single int value in parentheses. Ex. nap(15); An access modifier specifies whether other classes can use a particular field or invoke a particular method. The access modifiers in Java are public, protected, package-private (no modifier), and private. The most common optional specifiers are the following: o static is used for class methods. o abstract is used when a method does not have a body. o final is used when a method is not allowed to be overridden by a subclass. Return type is the data type of the value returned by the method, or void if the method does not return a value. The method name should follow the naming convention rules below: o Should be a verb in lowercase (ex. run); or o A multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc., that starts with capital letters (ex. runFast) The parameter list is a comma-delimited list of input parameters, preceded by their data types and enclosed by parentheses. Empty parentheses are allowed if there are no parameters specified. Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 The optional exception list indicates that the method might throw one of the listed exception types. The method body is everything that is enclosed between braces. It contains the method’s code including the declaration of local variables. Access Modifiers Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: Top level – public or package-private (no explicit modifier). Member level – public, private, protected, or package-private The public modifier allows the method to be visible to all classes everywhere. The private modifier specifies that the method can only be accessed in its own class. The package-private modifier specifies that the member can only be accessed within its own package. The protected modifier (no modifier) specifies that the member can only be accessed within its own package and by a subclass of its class in another package. A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes). At the member level, you can also use the public modifier or no modifier (package-private) just as with top level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package. The following table shows the access to members permitted by each modifier. Access Levels Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 The following figure shows the four classes in this example and how they are related. Classes and Packages of the Example Used to Illustrate Access Levels The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them. Visibility Modifier Alpha Beta Alphasub Gamma public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N REFERENCES: Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning Java programming: The object-oriented approach. Indiana: John Wiley & Sons, Inc. Farrell, J. (2014). Java programming (7th ed.). Boston: Course Technology, Cengage Learning. Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 STATIC METHODS AND FIELDS Fundamentals A static variable or class variable is any field declared with the static modifier; this tells the compiler that there is exactly one (1) copy of this variable in existence, regardless of how many times the class has been instantiated. Example: public class StaticVarDemo { static int count = 0; public void increment() { count++; } public static void main(String args[]) { StaticVarDemo obj1 = new StaticVarDemo(); StaticVarDemo obj2 = new StaticVarDemo(); obj1.increment(); System.out.println("Obj1: count = "+ obj1.count); obj2.increment(); System.out.println("Obj1: count = "+ obj1.count); System.out.println("Obj2: count = "+ obj2.count); } } Output: Objt1: count = 1 Objt1: count = 2 Objt2: count = 2 Explanation: count is a static variable, while increment is a method whose task is to increase the value of the count variable by 1. In the main method, two (2) objects are created, named obj1 and obj2. obj1 invoked the increment method and showed the value of 1. Then, obj2 also invoked the increment method, resulting in obj1 having also the value of 2. This is because count is a static variable. Only a single copy of a static variable is created and shared among all the instances of the class. Page 1 of 5 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 A static method belongs to the class rather than the object of a class. It can be invoked without creating an instance of a class. It can access static members and change their values. Static methods have two (2) main purposes: For utility or helper methods that don’t require any object state: Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method. For a state shared by all instances of a class (like a counter): All instances must share the same state. Methods that merely use that state should be static as well. To call a static method or variable, put the class name before the method or variable. Example: class NumberClass { public static int num = 10; public static void displayNumber() { System.out.print(num); } } public class NumberClassDemo { public static void main(String[] args) { System.out.print(NumberClass.num); NumberClass.displayNumber(); } } Output: 1010 An instance of an object can be used to call a static method or update a static variable. Example: public class NumberClass { public static int num = 0; public static void main(String[] args) { NumberClass.num = 4; NumberClass nc1 = new NumberClass(); NumberClass nc2 = new NumberClass(); nc1.num = 6; nc2.num = 5; System.out.print(NumberClass.num); } } Output: 5 Explanation: There is only one (1) num variable since it is static. Page 2 of 5 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 Static versus Instance An instance variable or method is any variable or method that is non-static. o It requires an object of its class to be created before it can be used or called. An instance variable is any variable that is declared outside any method, constructor, or block. Type Accessing Legal? How? Another static Static method Yes Using the class name method or variable An instance method Static method No or variable A static method or Using the class name Instance method Yes variable or reference variable Another instance Using a reference Instance method Yes method or variable variable Example of a static method calling an instance method: public class NumberClass { public static int num = 0; public static void main(String[] args) { displayNumber(); //does not compile } public void displayNumber() { System.out.print(num); } } Example of a static method trying to access an instance variable: public class NumberClass { int num = 0; public static void main(String[] args) { System.out.print(num); //does not compile } public void displayNumber() { System.out.print(num); } } REFERENCES: Oracle Docs (n.d.). Citing sources. Retrieved from- https://docs.oracle.com/javase/tutorial/java/javaOO/index.html Page 3 of 5 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 INSTANCE Variables Instance variables are declared in a class, but outside a method, constructor or any block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables. The instance variables are visible for all methods, constructors, and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers. Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName. import java.io.*; public class Employee { // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName) { name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal) { salary = empSal; } // This method prints the employee details. public void printEmp() { System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]) { Employee empOne = new Employee("Juana"); empOne.setSalary(1000); empOne.printEmp(); } } Page 4 of 5 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 STATIC Method and Variable Static methods as name states defined at the class level and could be accessed on the class name i.e no need of class object creation in order to access/call the static methods. While on another hand if we do not uses the static keyword with variable/method than it belongs or categorized as instance method which is defined at instance level and need class object for their accessibility. Also static methods exist as a single copy for a class while instance methods exist as multiple copies depending on the number of instances created for that particular class. Static methods can't access instance methods/variables directly while instance methods can access static variables and static methods directly. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks. Static variables can be accessed by calling with the class name ClassName.VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables. import java.io.*; public class Employee { // salary variable is a private static variable private static double salary; // DEPARTMENT is a constant public static final String DEPARTMENT = "Development "; public static void main(String args[]) { salary = 1000; System.out.println(DEPARTMENT + "average salary:" + salary); } } Page 5 of 5 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 METHOD OVERLOADING Passing Information to a Method Parameters are the variables listed in a method declaration. Ex. public double computeSalePrice(double origPrice, double discountRate) { } Arguments are the actual values that are passed in when the method is invoked. Ex. computeSalePrice(37.50, 0.15) Java is a pass-by-value language. When a parameter is pass-by-value, the caller and the callee method operate on two different variables which are copies of each other. Any changes to one variable don't modify the other. Ex. main() method calls newNumber() method public static void main(String[] args) { int num = 1; newNumber(2); System.out.println(num); } public static void newNumber(int num) { int num = 3; } Output: 1 Explanation: The variable num in main() does not change even after calling it because no assignments are made to it. Overloading Methods A method signature consists of the method’s name and the parameter types. Ex. The method signature of computeSalePrice(double origPrice, double discountRate) is computeSalePrice(double, double) Method overloading occurs when there are different method signatures with the same name but different type parameters. Ex. public void draw(String s) { } public void draw(double f, int i) { } public void draw(int i, double f) { } Thus, you can create statements like the following: draw(“Circle”); draw(3.3, 10); draw(10, 5.0); Overloaded methods are differentiated by the number and the type of arguments passed into the method. You cannot declare more than one (1) method with the same name and the same number and type of arguments. You cannot declare two (2) methods with the same signature even if they have different return types. Ex. public void draw(int i) { } public int draw(int i) { } // does not compile Page 1 of 2 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 METHOD OVERLOADING Autoboxing Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. Ex. int to Integer, double to Double The compiler automatically handles the conversion when a primitive value is − o Passed as an argument to a function which is expecting a wrapper class object. o Assigned to a variable of the type of wrapper class. Unboxing is reverse of Autoboxing and it refers to the automatic conversion of a wrapper object to its corresponding primitive variable. The compiler automatically handles the conversion when a wrapper object is − o Passed as an argument to a function which is expecting a primitive data type variable. o Assigned to a variable of the type of primitive data type variable. o A Wrapper class is a class whose object wraps or contains primitive data types. o Wrapper classes have predefined methods for performing useful operations on primitive data types. o Wrapper classes convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value). o Use of wrapper classes String s = “45”; int a = Integer.parseInt(s); // sets the value of a to 45. When the primitive type version is not present, Java performs autoboxing. public void draw(Integer i) { System.out.print(“Integer”); } Calling statement: draw(10); Output: Integer When the primitive type version is present, Java does not need to perform autoboxing. Ex. public void draw(Integer i) { System.out.print(“Integer”); } public void draw(int i) { System.out.print(“int”); } Calling statement: draw(10); Output: int REFERENCES: Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning Java programming: The object-oriented approach. Indiana: John Wiley & Sons, Inc. Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html Page 2 of 2 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 CONSTRUCTORS Fundamentals A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. o Every time an object is created using the new() keyword, at least one constructor is called. Ex. Employee emp = new Employee(); o A constructor performs operations required to initialize the class before methods are invoked or fields are accessed. Ex. public Employee() { salary = 15000; } Explanation: Every Employee object created will have a default starting salary of 15000 per month. o Constructors are never inherited. How Constructors are Different from Methods in Java? Constructors must have the same name as the class within which it is defined while it is not necessary for the method in Java. Constructors do not return any type while method(s) have the return type or void if does not return any value. Constructors are called only once at the time of Object creation while method(s) can be called any number of times. If you do not include any constructors in a class, Java provides a default constructor, a constructor with an empty parameter list and body. This is invisibly added to the class. It is also known as a no-argument constructor. Ex. public Employee () { } A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor. The this keyword is used when the instance variable has the same name with the constructor’s parameter. Example: public class Employee { private double salary; public Employee(double salary) { this.salary = salary; } } o Constructor(s) of a class must have the same name as the class name in which it resides. o A constructor in Java cannot be abstract, final, static, or synchronized. o Access modifiers can be used in constructor declaration to control its access. Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 CONSTRUCTORS Constructor Overloading Constructor overloading occurs when constructors have different type of parameters. Just Like methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. Example: public class Student { private String name; private int age; public static void main(String []arg) { public Student ( ) { Student s1 = new Student(); name = “No name yet.”; System.out.println (s1.name + “,”+ s1.age); age = 0; } s1.name = “Nissi”; s1.age = 14; public Student(String name, int age) { this.name = name; Student s2 = new Student (“Jireh”, 20); this.age = age; } System.out.println (s2.name + “,”+ s2.age); } } Explanation: Instances of the Student class can be created with or without arguments. Student s1 = new Student(); calls the default constructor because it does not have arguments. When a constructor calls another constructor with a greater number of parameters, it is called constructor chaining. This is accomplished using the this keyword too. The this() call must be the first statement in the constructor. Example: public Student() { this("No name yet."); } public Student(String name) { this(name, 0); } public Student(String name, int age) { this.name = name; this.age = age; } REFERENCES: Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 ENCAPSULATION Fundamentals Encapsulation describes the ability of an object to hide its data and methods. Encapsulation is also known as “data hiding.” Benefits of encapsulation: - It improves maintainability, flexibility, and reusability. - The fields can be made read-only or write-only. - It restricts access only to those features of an object that are declared public. In Java, a class encapsulates the fields, which holds the state of an object, and the methods, which define the actions of the object. Fields are encapsulated by declaring instance variables as private and methods as public. An accessor or a getter method is a public method that returns data from a private instance variable. A mutator or a setter method is a public method that changes the data stored in one or more private instance variables. Example: public class Student { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } Rules in Implementing Encapsulation 1. Instance variables are declared private. Ex. private String name; 2. Names of getter methods begin with get if the property is not a boolean. Ex. public String getName() { return name; } 3. Names of getter methods begin with is if the property is a boolean. Ex. public boolean isEnrolled() { return status; } 4. Names of setter methods begin with set. Ex. public void setName(String name) { this.name = name; } Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 Immutable Classes A class is considered immutable if it remains unchanged after an object of another class is constructed. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. For a class to be immutable, remove the setter methods and use the constructor for setting the values. How to create a custom immutable class in Java? Declare the class as final so it cannot be extended. All class members should be private so they cannot be accessed outside of class. Shouldn't contain any setter methods to change the value of class members. The getter method should return the copy of class members. Class members are only initialized using constructor. // class is declared final final class Immutable { // private class members private String name; private int date; Immutable(String name, int date) { //a constructor // class members are initialized using constructor this.name = name; this.date = date; } // getter methods that return the copy of class members public String getName() { return name; } public int getDate() { return date; } } class Main { public static void main(String[] args) { // create object of Immutable class Immutable obj = new Immutable("Jeremiah", 2911); System.out.println("Name: " + obj.getName()); System.out.println("Date: " + obj.getDate()); } } Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 REFERENCES: Savitch, W. (2014). Java: An introduction to problem solving and programming (7th ed.). New Jersey: Pearson Education, Inc. Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html https://www.programiz.com/java-programming/examples/create-immutable-class Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 INHERITANCE Fundamentals Inheritance allows a class to acquire all the attributes (fields) and behaviors (methods) of another class. A class that is derived from another class is called a subclass. It is also known as derived class or child class. The class from which the subclass is derived is called a superclass. It is also known as base class or parent class. extends keyword is used to perform inheritance Example: public class Person{ private String name; public void setName (String name){ this.name = name; } public String getName(){ return this.name; } class Student extends Person { public static void main (String [] args) { System.out.println(getName()); } } Explanation: Student is the subclass while Person is the superclass. Assuming that both classes are in the same package, an import statement is not required in Student.java to access the Person class. In Java, inheritance is an IS-A relationship. Inheritance is used if there is an is-a relationship that exists between two classes. Types of Inheritance: Java supports multiple levels of inheritance where a class may extend another class, which in turn extends another class. Example: public class Person { } public class Student extends Person { } public class FirstYear extends Student { } Java supports single inheritance where a class may inherit from only one (1) direct parent class. Java supports hierarchical inheritance where multiple subclasses extend from a single superclass. Extending multiple classes (multiple inheritance) are not allowed. 06 Handout Page 1 of 6 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 INHERITANCE Fundamentals In Java, all classes inherit from the Object class. It is the only class that does not have any parent classes. //Class declaration 1 public class Student { } //Class declaration 2 public class Student extends java.lang.Object { } Explanation: Both class declarations mean the same. A class that does not extend another class invisibly extends the Object class. To prevent a class from being extended, mark the class with the final modifier. Even though the superclass is public, its subclass cannot access its private fields. Example: //Person.java public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } //Student.java public class Student extends Person { public static void main(String[] args) { System.out.println(name); //does not compile } } Explanation: The name variable in the Person class is marked as private and therefore not accessible from the subclass Student. Inheritance is useful for code reusability. The code that is present in the parent class can be directly used by the child class. You can define a new version of an existing method in a child class that makes use of the definition in the parent class. This ability is called method overriding. 06 Handout Page 2 of 6 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 Java Overriding Rules Both the superclass and the subclass must have the same method name, the same return type and the same parameter list. The method in the subclass must be at least as accessible as the method in the parent class. We cannot override the method declared as final and static. We should always override abstract methods of the superclass The @Override annotation specifies the compiler that the method after this annotation overrides the method of the superclass. Example: //Superclass public class FirstClass { protected String getMessage() { return "Method"; } } //Subclass class SecondClass extends FirstClass { public String getMessage() { return super.getMessage() + " Overriding"; } public static void main(String[] args) { System.out.println(new SecondClass().getMessage()); } } Output: Method Overriding Explanation: The getMessage() method of SecondClass overrides getMessage() of FirstClass. The super keyword can be used to access the method of the parent class being overridden. Uses of super keyword The super keyword in Java is used in subclasses to access superclass members (attributes, constructors and methods). To call methods of the superclass that is overridden in the subclass. To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor. 06 Handout Page 3 of 6 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 Rules in Defining Constructors 1. The first statement of every constructor is either a call to another constructor within the class using this() or a call to a constructor in the direct parent class using super(). Example: public class Person { // parent class or superclass private String name; public Person(String name) { // constructor of superclass this.name = name; System.out.println(this.name); } } class Student extends Person { // subclass Student(String name){ // 1st constructor super(name); // call to the no-arg constructor of the superclass } Student() { //2nd constructor this("no name yet"); // a call to other constructor within the same class Student } } Explanation: In the Student class, the first statement of the first constructor is a call to the constructor of the Person class. It also includes another no-argument constructor that calls the other constructor within the class using this("No name yet."). 2. The super() command may only be used as the first statement of the constructor. Example: public Person() { System.out.println("Person object created."); super(); //does not compile } Explanation: The super() command is the second statement and therefore will lead to a compilation error. 3. If a super() call is not declared in a constructor, Java will insert a no-argument super() as the first statement of the constructor. Example: //Empty Constructor public Student() { } //Equivalent to the empty constructor public Student() { super(); 06 Handout Page 4 of 6 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 } Explanation: The Java compiler invisibly adds a no-argument constructor super() if the first statement is not a call to the parent constructor. 4. If the parent class does not have a no-argument constructor and the child class does not define any constructors, the compiler will throw an error. This is because the child class has an invisible no-argument super() that tries to call the constructor of the parent class. Example: //Person.java public class Person { private String name; public Person(String name) { this.name = name; } } class Student extends Person { } //above does not compile Explanation: The compiler adds a no-argument constructor and a no-argument super(). However, the Person class does not have a no-argument constructor, leading to a compilation error. 5. If the parent class does not have a no-argument constructor, the compiler requires an explicit call to a parent constructor in each child constructor. Example: //Person.java public class Person { private String name; public Person(String name) { this.name = name; } } class Student extends Person { public Student(){ super("Nissi"); } } Explanation: The constructor in Person can only be called if the Student specifies a String argument in the super() call of its constructor such as super("Nissi") 06 Handout Page 5 of 6 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 Calling Constructors and Overriding Methods The parent constructor is always executed before the child constructor. Example: //Person.java public class Person { public Person() { System.out.println("Person"); } } class Student extends Person { public Student() { System.out.println("Student"); } } class FirstYear extends Student { public static void main(String[] args) { FirstYear fy = new FirstYear(); } } Output: Person Student Explanation: The compiler first inserts invisible super() commands as the first statements of both Person and Student constructors. Next, the compiler inserts an invisible default no-argument constructor in the FirstYear class with an invisible super() as the first statement of the constructor. REFERENCES: Savitch, W. (2014). Java: An introduction to problem solving and programming (7th ed.). New Jersey: Pearson Education, Inc. Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html 06 Handout Page 6 of 6 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 POLYMORPHISM Fundamentals Polymorphism allows performing of a single action in different ways. Types of Polymorphism: Static – Flow of control is decided during compile time. It is achieved through method overloading. public void draw(String s) { } public void draw(int i) { } public void draw(int i, double f) { } Dynamic – Flow of control is decided during runtime. It is achieved through method overriding. public class Class1 { public String message() { return "Method"; } } public class Class2 extends Class1 { public String message() { return super.message() + " Overriding";} public static void main(String[] args) { System.out.print(new Class2().message()); } } Object Casting You can change the existing type of an object reference to another type through casting. Upcasting is casting from a subclass to a superclass. public class Animal { } public class Cat extends Animal { public static void main(String[] args) { Cat c = new Cat(); Animal a = c; } } Downcasting is casting from superclass to a subclass. public class Animal { } public class Cat extends Animal { public static void main(String[] args) { Animal a = new Cat(); Cat c = (Cat)a; } } 09 Handout Page 1 of 3 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 POLYMORPHISM Rules in Casting Objects 1. The compiler will not allow casts to unrelated types. public class Dog { } public class Cat { public static void main(String[] args) { Cat c = new Cat(); Dog d = (Dog)c; //does not compile } Explanation: There is no inheritance between the two (2) classes. 2. Even when the code compiles without issue, an exception may be thrown at runtime if the object being cast is not actually an instance of that class. public class Animal { } public class Cat extends Animal { public static void main(String[] args) { Animal a = new Animal(); Cat c = (Cat)a; //Throws ClassCastException at runtime } Explanation: Object a is not an instance of Cat. Rules in Overriding Methods 1. The method in the child class must have the same signature as the method in the parent class. public class ClassA { public String message() { return "Method"; } } public class ClassB extends ClassA { public String message() { return " Overriding"; } } 2. The method in the child class must be at least as accessible or more accessible than the method in the parent class. public class ClassA { protected String message() { return "Method"; } } public class ClassB extends ClassA { private String message() { //does not compile return " Overriding"; } } Explanation: The message() method is marked protected in the superclass and private in the subclass. To resolve this issue, message() in the subclass should be marked public or protected. 09 Handout Page 2 of 3 Bulacan State University College of Information and Communications Technology IT 207- Object-Oriented Programming 2 3. The method in the child class may not throw a checked exception that is new or broader than the class of any exception thrown in the parent class method. //Example 1 public class ClassA { public String message() { return "Method"; } } public class ClassB extends ClassA { public String message() throws Exception { return " Overriding"; } } Explanation: The message() method in the superclass doesn't throw an exception. //Example 2 public class ClassA { public String message() throws ArithmeticException { return "Method"; } } public class ClassB extends ClassA { public String message() throws Exception { return " Overriding"; } } Explanation: The message() method in the subclass throws a broader exception than message() in the superclass. REFERENCES: Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html 09 Handout Page 3 of 3 Bulacan State University College of Information and Communications Technology IT 203- Object-Oriented Programming ABSTRACTION Fundamentals Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces. Importance of Abstraction: 1. Simplifies Code: It reduces complexity by allowing programmers to focus only on the core functionality. 2. Improves Code Reusability: Abstract classes and interfaces can be used as blueprints; they promote consistency and can be reused across multiple parts of a program. 3. Enhances Flexibility and Scalability: It can easily make modifications. The abstract keyword is a non-access modifier, used for classes and methods: Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). An abstract class can have both abstract and regular (concrete) methods: An abstract class is created to ensure that subclasses will implement necessary methods. Example: public abstract class Pet{ private String name; public abstract void eat(); public String getName(){ return this.name; } public class Cat extends Pet { public void eat(){ } } Explanation: The Cat class extends its parent class, Pet. Then, it has to use the method eat(). An abstract method is required to be implemented by subclasses. It is declared without braces but with a semicolon. Example: abstract void makeSound(); 07 Handout Page 1 of 3 Bulacan State University College of Information and Communications Technology IT 203- Object-Oriented Programming Key Considerations in Abstraction: 1. Identify Common Features: When designing a system, first identify which features are common across different types of objects or entities. For instance, in a payroll system, all employee types (like part-time or full-time) will have a common feature: calculating their pay. 2. Define Essential Operations: Decide on the operations or methods that are crucial but need to be implemented differently based on specific requirements. In a school system, for instance, every person may have a getDetails() method, but each type (e.g., Student, Teacher, Staff) might implement it differently. 3. Use Abstract Classes and Interfaces Wisely: Use abstract classes when you have a base class that shares some common attributes or partial implementation with subclasses. Use interfaces to define a contract or capabilities that different classes should implement, especially when classes come from different parts of the program but share behavior. 4. Minimize Dependencies: Abstraction helps reduce dependency by hiding complex logic inside abstract classes or interfaces, making the system easier to maintain and extend. Rules in Defining Abstract Classes 1. An abstract class cannot be instantiated directly. Example: public abstract class Pet { public static void main(String[]args){ Pet p = new Pet(); // compiler error } } 2. An abstract class may include non-abstract methods and variables. 3. An abstract class cannot be marked as final, because a final class cannot be extended by another class. 4. An abstract class that extends to another abstract class inherits all of its abstract methods as its own abstract methods. 5. The first concrete class (non-abstract class that extends an abstract class) is required to implement all inherited abstract methods. Example: public abstract class Animal { public abstract void sleep(); } public abstract class Pet extends Animal { public abstract void eat(); } public class Cat extends Pet { public void sleep() {} public void eat() {} } 07 Handout Page 2 of 3 Bulacan State University College of Information and Communications Technology IT 203- Object-Oriented Programming Rules in Defining Abstract Methods 1. An abstract method may only be defined in an abstract class. Example: public class Pet{ public abstract void eat(); // compiler error } 2. An abstract method cannot be marked as final because a final method cannot be overridden in a subclass. Example: final abstract void eat(); // compiler error 3. An abstract method cannot be marked as private since that method is only accessible to the class where it belongs to. Example: private abstract void eat(); // compiler error 4. To override an abstract method, declare a new method with the same name, parameter list, and return type as the method in the parent class. The method in the subclass must be at least as accessible as the method in the parent class. Example: public abstract class Pet { protected abstract double getAge(); } public class Cat extends Pet { @Override public double getAge() { return 5.0; } } The @Override annotation specifies the compiler that the method after this annotation overrides the method of the superclass. REFERENCES: Savitch, W. (2014). Java: An introduction to problem solving and programming (7th ed.). New Jersey: Pearson Education, Inc. Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html 07 Handout Page 3 of 3 Bulacan State University College of Information and Communications Technology IT 203- Object-Oriented Programming INTERFACE Fundamentals An interface is a collection of related abstract public methods. It can also contain default methods, static methods, and constants declaration. An interface is a completely "abstract class" that is used to group related methods with empty bodies. An interface is created and defined using the interface keyword. public interface Drinkable { public static final int MAX_GLASSES = 0; //constant declaration public abstract int getNumGlasses(); // abstract method } Can be written as: public interface Drinkable { int MAX_GLASSES = 0; //constant declaration int getNumGlasses(); // abstract method } Explanation: Methods are implicitly public; there is no need to use this keyword in the method declaration. Constants are implicitly public, static, and final. These keywords are not required in the declaration of a constant. To access the interface methods, the interface must be "implemented" (kind of like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class: Like abstract classes, interfaces cannot be used to create objects. Interface methods do not have a body - the body is provided by the "implement" class On implementation of an interface, you must override all of its methods Interface methods are by default abstract and public Interface attributes are by default public, static and final An interface cannot contain a constructor (as it cannot be used to create objects) Importance of Interfaces: ✓ To achieve security - hide certain details and only show the important details of an object (interface). ✓ Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. 08 Handout Page 1 of 2 Rules in Defining an Interface 1. An interface cannot be instantiated directly. Example: public interface Engine { } class Car { public static void main(String[]args){ Engine e = new Engine (); // error - abstract cannot be instantiated } } 2. It is not required for an interface to have a method. 3. An interface cannot be marked as final. public final interface Engine {} // compiler error 4. Interfaces are assumed to be an abstract. Example: public interface Engine {} is equivalent to public abstract interface Engine {} 5. All abstract, default, and static methods in an interface are implicitly public. Rules in Inheriting an Interface 1. An interface that extends another interface, as well as an abstract class that implements an interface, inherits all of the abstract methods as its own abstract methods. 2. The first concrete class that implements an interface, or extends an abstract class that implements an interface, must provide an implementation for all of the inherited abstract methods. 3. A class cannot extend an interface. 4. An interface cannot extend a class. REFERENCES: Savitch, W. (2014). Java: An introduction to problem solving and programming (7th ed.). New Jersey: Pearson Education, Inc. Oracle Docs (n.d.). Citing sources. Retrieved from https://docs.oracle.com/javase/tutorial/java/javaOO/index.html 08 Handout Page 2 of 2 Default Methods: Allow you to add new functionalities to interfaces without breaking existing implementations. Promote reusability by providing optional, reusable implementations for common behaviors. Static Methods: Provide a way to include utility methods directly in the interface, making the code more organized. Allow related functionality to be bundled together, which keeps the code cohesive and easier to read. The addition of default and static methods in interfaces in Java 8 has indeed made interfaces more similar to abstract classes, as both can now provide concrete method implementations. However, some important differences remain between interfaces and abstract classes: 1. Multiple Inheritance Interface: A class can implement multiple interfaces, which is Java’s way of supporting multiple inheritance. This allows a class to inherit behavior from multiple sources. Abstract Class: A class can only inherit from one abstract class due to Java’s single inheritance model for classes. Example: interface A {} interface B {} class C implements A, B {} // Multiple interfaces allowed abstract class X {} abstract class Y {} class Z extends X, Y {} // Error: Cannot extend more than one class 2. Nature of Methods and Use Cases Interface: Primarily used to define a contract that unrelated classes can implement. Interfaces are generally used for behaviors that can be shared across different classes. Abstract Class: Best used for classes that represent a common base with shared behavior or state. An abstract class is ideal when you want to provide a base implementation for subclasses or share fields. 3. Fields/State Interface: Can only have public static final fields (i.e., constants). Interfaces cannot hold instance variables or state. Abstract Class: Can have instance variables (fields) that represent shared state, which can be used and modified by its subclasses. interface Config { int MAX_RETRIES = 5; // Constant } abstract class Vehicle { protected int speed; // Instance variable } 4. Constructors Interface: Cannot have constructors, as interfaces are not intended to be instantiated directly. Abstract Class: Can have constructors, which can be called by subclasses to initialize common fields. interface Tool { // No constructors allowed } abstract class Machine { Machine() { System.out.println("Machine initialized"); } } 5. Inheritance of Concrete Methods Interface: Methods in interfaces must be public by default. They can have default implementations or be static but cannot be protected or private (except for helper methods, which can be private). Abstract Class: Can have any access modifier (public, protected, or private) for its methods. Abstract classes allow greater control over the visibility and scope of methods. interface Action { default void perform() { System.out.println("Performing action"); } } abstract class Task { protected void execute() { System.out.println("Executing task"); } } 6. When to Use Each Interface: Use interfaces when you want to define a contract for unrelated classes to follow or when you need to specify behaviors (like Runnable, Serializable). Interfaces are ideal for defining capabilities that different classes can implement in their own way. Abstract Class: Use abstract classes when there’s a close relationship between classes that share common behavior or state. Abstract classes are suitable when you want to provide a default implementation or state for a group of related classes. Summary Table Feature Interface Abstract Class Multiple Inheritance Yes No Fields public static final constants only Instance variables allowed Methods Abstract, default, and static only Abstract or fully implemented Constructors Not allowed Allowed Access Modifiers Public (or private for helper methods) Any (public, protected, private) Purpose Define a contract (capability) Common base with shared behavior or state Bulacan State University College of Information and Communications Technology IT 203- Object-Oriented Programming UML CLASS DIAGRAM Fundamentals A UML (Unified Modeling Language) Class Diagram is a visual representation of the classes in a system and how they relate to each other. It’s a foundational tool in object-oriented programming (OOP) for planning the structure of a program before writing any code. Why Use UML Class Diagrams? o Helps organize and visualize the structure of your system. o Identifies relationships and dependencies between different components. o Provides a clear design roadmap, especially useful for larger projects. Components of a Class in UML Structure of a Class in UML - Each class is represented by a rectangle divided into three parts: 1. Class Name: The name of the class, written in the top section. 2. Attributes: The properties or variables the class holds, written in the middle section, - often with visibility symbols (+ for public, - for private, # for protected). 3. Methods: The actions or behaviors the class can perform, listed in the bottom section, with visibility symbols and parameters (e.g., + getName(): String). Objects - The instance of a class, often illustrated as rectangles with the object’s name underlined. Access Modifiers in UML o + for public (accessible everywhere). o - for private (accessible only within the class). o # for protected (accessible within the class and its subclasses). Types of Relationships: o Association: - A basic connection between classes. Represents a general link between two classes, showing that they interact in some way. - Associations can have multiplicity to show the number of instances involved (e.g., one-to-many, Student enrolls in a Course). o Inheritance: - Represents an "is-a" relationship where a subclass inherits properties and behaviors from a superclass. - Shows that a class is derived from another class (indicated with a hollow triangle arrow). (e.g., GraduateStudent inherits from Student). o Aggregation: - Represents a "has-a" relationship where one class contains another but isn’t dependent on it. - A "whole-part" relationship, where one class contains a reference to another. It indicates that the part can exist independently. (e.g., a Department has many Professors). o Composition: - A stronger "has-a" relationship where one class is an essential part of another, indicating ownership where the part cannot exist without the whole (e.g., a Library has Books that do not exist outside of it). Interfaces - An interface defines a contract that classes can implement. It contains only method declarations, without implementations. - Useful for defining common behaviors across unrelated classes. Abstract Classes and Methods - A class that cannot be instantiated on its own and may contain abstract methods. - A method declared without an implementation, intended to be overridden in subclasses. Example of a Class Diagram for a Simple Enrollment System Imagine a system where students enroll in courses managed by a professor. Here’s a basic diagram to illustrate: Diagram Example: UML Class Diagram: 1. Classes: Ex 1: o Student o Course o Professor 2. Attributes: o Student: studentID, name o Course: courseID, courseName, credits o Professor: professorID, name 3. Relationships: Ex. 2: o Student - Course (Association, as a student can enroll in multiple courses). o Professor - Course (Aggregation, as a professor teaches many courses). Bulacan State University IT 207 College of Information and Communication Technology Object-Oriented Programming 2 EXCEPTION HANDLING Exception handling in Java is a mechanism that allows you to handle errors or exceptional situations that may occur during the execution of a program. Java Exception Hierarchy The Throwable class is at the top of the exception hierarchy following which are the subclasses-Error and Exception. Error and Exception should not be confused as same because there is a huge difference between these two classes. Where an exception is an unwanted event in a program that can be handled within the program the error cannot be handled in a program as it is a much serious condition that causes damage to the architecture. Examples of Exceptions: IllegalArgumentException, ClassNotFoundException and NullPointerException. Examples of Error: InternalError, OutOfMemoryError and AssertionError. Two Types of Exceptions: 1. Checked are the compile-time exceptions. 2. Unchecked are Runtime exceptions. Additional subclasses of RuntimeException are unchecked and other than this are checked ones. Using the Throws keyword The throws keyword defines that the method will throw an exception Once the exception is thrown the caller has to handle it using a try-catch block. We can throw either checked or unchecked exceptions. The throws keyword provides information about the type of exception the method may throw but does not prevent the program from getting aborted. Catching specific Java exceptions A try-catch method is the best way to handle exceptions. To catch specific Java exceptions a try block can be followed by one or more catch blocks, each specifying a particular type. If there’s an exception in the try block, the exception is thrown to the first catch block, if not caught by this class it is passed on until it gets caught or misses all. THE USE OF TRY & CATCH: - It allows us to manually handle the exception - It allows to fix errors - It prevents the automatic termination of the program in cases when an exception occurs The finally block The finally block is for the code that is to be executed in every case, whether there is an exception or not. It means the finally block is executed every time. Best Practices: Catch Specific Exceptions: Catch specific exceptions rather than catching generic Exception. This lets you handle different exceptions differently and provide more meaningful error messages. Logging: Use logging frameworks like Log4j or java.util.logging to log exceptions and other relevant information. Logging helps in debugging and troubleshooting issues. Graceful Handling: Handle exceptions gracefully by providing appropriate error messages to the user and taking corrective actions whenever possible. Resource Management: Use the try-with-resources statement for automatic resource management, especially when dealing with I/O operations or database connections. This ensures that resources are properly closed even if an exception occurs. Exception handling is an essential aspect of writing robust and reliable Java applications. By handling exceptions appropriately, you can improve the stability and user experience of your software.