Today we touched briefly upon the concept of interfaces and exceptions. Here is what we have learnt so far.
Interface
A special function that is hard to find in other languages except for Java.
An interface is a completely abstract class that is used to group related methods with empty bodies.
It can only contain abstract methods and constants (think static final).
interface AAA{
public static final int NUMBER = 0;
public void print(); //인터페이스는 abstract 생략 가능
}
To access the interface methods, the interface must be implemented (similar to inheritance) by another class using the implements keyword. Look at the example below for a further dive into its use and process:
below is a sample interface. Note here that we did not use the abstract keyword for the print() method, this is because the keyword is omitted as it is common knowledge that an interface contains abstract methods.
interface AAA{
public static final int NUMBER = 0;
public void print(); //인터페이스는 abstract 생략 가능
}
As mentioned class BBB has implemented interface AAA:
Since we are using abstract elements within the interface, we use the @Override annotation to implement it.
class BBB implements AAA {
@Override
public void print() {//바디만 있어도 구현했다고 인지
}
Example 1: use of inheritance of class and multiple inheritances of interfaces:
//as seen below despite only being able to inherit one class, you can implement multiple interfaces using a comma ( , )
public class CCC extends DDD implements AAA, EEE {
@Override
public void print() {
// TODO Auto-generated method stub
}
@Override
public void play() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
EEE eee = new CCC(); // only superclasses can promote sub classes, not the other way around.
AAA aa = new CCC();
DDD dd = new CCC();
List<Integer> list = new ArrayList<Integer>();
}
}
Example 2: further use of interfaces and inheritance
- class Animal: super class
public class Animal {
String name;
int age;
public Animal(String name) {
this.name = name;
}
}
In the Animal class it has a constructor that makes it mandatory for all of its sub classes to take a String name as its parameter.
- class Cat: sub class
public class Cat extends Animal implements Predator {
public Cat(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public String getName() {
return this.name;
}
}
As seen here Cat inherits all of Animal's methods: retrieving and using the String: name instance, as well as those of the Predator interface: the getName(); abstract method by overriding.
- Predator : interface
public interface Predator {
public String getName();
}
- class ZooTrainer
package zoo;
public class ZooTrainer {
public void feed(Predator predator) {
System.out.println(predator.getName() + "에게 밥을 줍니다");
}
}
The ZooTrainer class then sets the Predator interface as its parameter and calls the getName() method as part of its sequence.
- class Zoo: main method
package zoo;
public class Zoo {
public static void main(String[] args) {
Cat cat = new Cat("Catcat");
Dog dog = new Dog("Zulu");
Rat rat = new Rat("Grey");
ZooTrainer trainer = new ZooTrainer();
trainer.feed(cat);
trainer.feed(dog);
trainer.feed(rat);
}
}
Therefore in the main method, each time a new Animal is called, it needs to take a String name to be constructed. As well as the trainer being able to call the .feed() method.
Exception
In Java we use exception to process and handle certain execution of code depending on our purpose.
Exception is defined as all instances of an error happening within an execution.
However there are certain APIs that doesn't compile at all if we do not process said exceptions during compiling.
In a nutshell: think of exceptions as all error messages and instances we face while coding!!
How an exception comes to be:
compiling > execution > coming across an exception during compiling > Virtual Machine figures out the type of exception and its details > exception variable is formed > the variable is throw(thrown) > moves to the exception call stack > moves over to main method > forced termination
We throw exceptions and since exceptions are a variable they have a class they belong to.
Exception and its classes
The highest class of Exceptions are is Throwable in the lang package.
Their sub classes are Error and Exception.
- Error sub classes are usually defined as classes that are related to errors within the Java Virtual Machine. Therefore these problems cannot be processed by the programmer themselves as it is a problem of Java Runtime Engine as a whole. Therefore the programmer's role isn't to solve these sub class errors as they are non-executionable.
- Exception sub classes are the types of exceptions that programmers process. The highest classes for these is Exception. Throwable class has Error as its sub class, so we do not claim it as the highest type of exception.
Types of Exceptions : 2 types
- Checked Exception
Exception that is checked during compiling, this is when the compiler takes an active role in checking. - Unchecked Exception
Exception that is not checked during compilation, also all sub classes under RuntimeException which is a sub class of Exception are Unchecked Exceptions.
So what do we do if we come across an exception, how can we fix it?
We use the Try and Catch(and finally) method!
Example 1:
Unchecked Exception: ArrayIndexOutOfBoundsException
public class Exception01 {
public static void main(String[] args) {
System.out.println("main 시작");
int[] arr = { 10, 20, 30, 40, 50 };
try {
// a command that might bring up an exception (usually Java recommends you use it after you type it)
System.out.println(arr[5]);
} catch (Exception e) {
//a command that will excecute if there is an exception, like below!
System.out.println("예외가 발생했어요");
}
System.out.println("main 끝");
}
}
But what's the point of a try and Catch method?? It doesn't fix anything!!
The point of using it is to have the code execute completely instead of being forcefully terminated in the middle once it runs into an exception! Besides we can use the try and catch to create a customised catch message to alert us if something did go wrong instead of looking for hours for where we went wrong.
Using MariaDB for Try and Catch
setting up MariaDB for Java1.) visit website > connector > select Java > download > keep jar file zipped
2.) Open Eclipse > select project: right click > build path > libraries> class path > add external jar > select file > apply
MariaDB will be under references libraries in the project folder :3
This is where we get to see the true magic of Try and Catch and how to use it to retrieve information from a database.
It was so fun to learn the methods behind it, I had such a great time learning :3
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Exception04 {
public static void main(String[] args) {
we create variable conn using Connection that will work as a keycard that will hold all info to access the DB
Connection conn = null;
we then create variable stmt using Statement that will work as a messenger between DB and us
Statement stmt = null;
Here we input all the needed info to be stored in conn
String url = "jdbc:mariadb://redacted/employees";
String id = "redacted";
String pw = "redacted";
this is where we store our command prompt that will be used to search the DB
String sql = "SELECT * FROM employees;";
try {
.forName( file path in the brackets ) method: which will direct Java to find the class with the same name
Class.forName("org.mariadb.jdbc.Driver");
next we assign the needed info(url, id, pw) into conn using DriverManager.getConnection method to establish connection
conn = DriverManager.getConnection(url, id, pw);
Then stmt uses .createStatement() on conn to connect us to the DB
stmt = conn.createStatement();
// System.out.println("데이터베이스에 접속하였습니다");
create variable rs with ResultSet that stores the data fetched from executeQuery method by the command stored in sql.
ResultSet rs = stmt.executeQuery(sql);
Then we process a while statement to turn each section of rs from index 1 till there is nothing left.
while (rs.next()) { since we don't know how many indexes there are in rs, we use the next() method, which is boolean
String text = rs.getString(1); storying each rs converted to String into text
System.out.println(text); printing text so we can read it :3
}
} catch (ClassNotFoundException e) {
System.out.println("올바른 드라이버가 설치되지 않았습니다. 관리자에게 문의하세요"); print if 1st try doesn't work
e.printStackTrace();
} catch (SQLException e) {
System.out.println("올바른 경로 또는 아이디와 암호를 입력하세요"); print if 2nd try doesn't work
e.printStackTrace();
} finally { this will be processed whether or not try or catch is activated
try {
stmt.close(); close stmt after we're finished
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close(); close conn after we're finished
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
'JAVA' 카테고리의 다른 글
Creating JSP: using lists and getter/setter & Collections continued (0) | 2024.07.04 |
---|---|
Importing data into JSP, Java Collection Framework: Lists (0) | 2024.07.03 |
Recap of Access Modifiers and deep dive into 4 pillars of OOP (0) | 2024.07.01 |
OOP continued: Static, access modifiers, Singleton pattern (0) | 2024.06.29 |
Object Oriented Programming: Fields, Constructors and methods (0) | 2024.06.27 |