Lec13 API Inheritance Exceptions InterfacesAudio
Lec13 API Inheritance Exceptions InterfacesAudio
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Java Interfaces
class Vehicle {
protected String brand = “Benz"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
Java Inheritance (Subclass and Superclass)
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
When executing Java code, different errors can occur: coding errors made
by the programmer, errors due to wrong input, or other unforeseeable
things.
When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception
(throw an error).
Java try and catch
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Java try and catch
If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:
The finally statement lets you execute code, after try...catch, regardless of
the result:
public class MyClass {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
The throw keyword
The throw statement is used together with an exception type. There are
many exception types available in Java: ArithmeticException,
ClassNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc.
Example
Throw an exception if age is below 18 (print "Access denied"). If age is
18 or older, print "Access granted":
public class MyClass {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}}