sse3052: embedded systems practicecsl.skku.edu/uploads/sse3052s18/6-java.pdf · sse3052: embedded...
TRANSCRIPT
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected])
SSE3052: Embedded Systems Practice
Minwoo Ahn
Computer Systems Laboratory
Sungkyunkwan University
http://csl.skku.edu
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 2
Agenda
• Learning Java!
– Installation
– Class, method, and object
– Inheritance
– Predefined class (String)
– Interface
– Exception handling
– ArrayList
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 3
Object oriented programming
https://kienthuc24h.com/wp-content/uploads/2017/07/class.jpg
▪ Color
▪ Type
▪ Fuel
▪ Company
Vehicle class
Inheritance
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 4
Installation
• JDK (Java Development Kit)– Check if JDK is installed (maybe not installed)
• $javac –version
– If not, install JDK
• $sudo apt install default-jdk
• Eclipse IDE
– Go to http://www.eclipse.org/downloads/
– Download “Eclipse IDE for Java Developers”
– Untar
– Execute “eclipse-inst”
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 5
Warm up (Hello World!)
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello World!”);
}
}
HelloWorld class
main method (~= function in C language)
public access modifier (public, private, protected)
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 6
C code vs. Java code
• C code
int funcA() {…}
int funcB() {…}
int funcC() {…}
int main() {
funcA();
funcB();
funcC();
}
• Java code
class classA {
int methodA() {…}
int methodB() {…}
int methodC() {…}
}
class classB {
int methodA() {…}
int methodB() {…}
int methodC() {…}
}
class classC {
static void main() {…}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 7
Class
• A class is a template that describes data and behavior
• Similar with “structure” in C language
Ex)class person {
String firstName; // Instance variable
public String getFirstName() { //Getter (method)
return firstName;
}
public void setFirstName(String firstName) { // Setter (method)
this.firstName = firstName;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 8
Constructor
class Person {
String firstName;
String lastName;
int age;
public void Person(String a, String b, int value) {
firstName = a;
lastName = b;
age = value;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return firstName + " " + lastName;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 9
Object
• An object is an instance of a class
Ex)
public class Main {
public static void main(String[] args) {
Person person = new Person(“Jim”, “Knopf”, 21);
Person p2 = new Person(“Jill”, “Sanders”, 20);
// Jill gets married to Jim
// and takes his name
p2.setLastName(“Knopf”);
System.out.println(p2); // “Jill Knopf” will printed
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 10
Constructor
• A special “method” that is invoked when creation of instance
• Name of constructor is ALWAYS the name of the class
• No return type
• One class can include several constructor (overloading)
• If no explicit constructor is defined, compiler implicitly adds a
constructor with default values
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 11
Example (3 constructors)class Person {
String firstName;
String lastName;
int age;
public Person() {
firstName = "No";
lastName = "Name";
age = 0;
}
public Person(String a, String b) {
firstName = a;
lastName = b;
age = 0;
}
public Person(String a, String b, int value) {
firstName = a;
lastName = b;
age = value;
}
…
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 12
Method overloading
• More than on method with the same name, different arguments
• Type of return value doesn’t matter
Ex)
Class PrintStream {
public void println(String s) {…}
public void println(double a) {…}
}
class PrintStream {
public void println(String s) {…}
public int println(String s) {…}
}
(O)
(X)
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 13
Exercise 1
• Implement a class circle that has methods double getArea() and
double getPerimeter(). In the constructor, supply the radius of the
circle. If radius is not given by user, default value is 10.
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 14
Inheritance
• A subclass which derived from superclass
Ex)
Class Person {
…
}
Class Students extends Person {
int grade;
public Student() {…}
}
Person
Student Doctor Professor
Superclass
Subclass
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 15
Example (Student derived from Person)class Student extends Person {
int grade;
public Student(String a, String b, int age, int grade) {
super(a, b, age); //Constructor of superclass Person
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String toString() {
return getFirstName() + " " + getLastName() + " is grade " + grade;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 16
Example cont. (Main)
class Main {
public static void main(String[] args) {
Student s1 = new Student("Bill", "Gates", 13, 9);
s1.setFirstName("Steve");
s1.setGrade(10);
System.out.println(s1);
//”Steve Gates is grade 10” will printed
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 17
Method overriding
• Method redeclarationEx)
class BaseClass {
public String toString() {
return “Base”;
}
}
class ChildClass extends BaseClass {
public String toString() {
return “Child”;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 18
Method overriding
public class Main {
public static void main(String[] args){
BaseClass a = new BaseClass();
ChildClass b = new ChildClass();
System.out.println(a); //”base”
System.out.println(b); //”child”
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 19
Available access modifier
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
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 20
String class
• String class represents array of characters
– All string literals are implemented as instances of String class
• Strings are immutable
• Initialization
– Ex) String s = “text”;
– Ex) String s = new String(“text”);
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 21
String methods• char charAt(int index)
– Returns the char value at the specified index.
• String concat(String str)
– Concatenates the specified string to be the end of this string.
• boolean endsWith(String suffix)
– Tests if this string ends with the specified suffix.
• boolean equals(Object anObject)
– Compares this string to the specified object.
• int indexOf(int ch)
– Returns the index within this string of the first occurrence of the specified character.
• int indexOf(String str)
– Returns the index within this string of the first occurrence of the specified substring.
• int length()
– Returns the length of this string.
• More APIs: https://docs.oracle.com/javase/8/docs/api/
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 22
Exercise 2
• Write a superclass Worker and subclasses HourlyWorker and SalariedWorker.
Every worker has a name and a salary rate. Write a method computePay(int
hours) that computes the weekly pay for every worker. An hourly worker
gets paid the hourly wage for the actual number of hours worked, if hours
is at most 40. If the hourly worker worked more than 40 hours, the excess
is paid at time and a half. The salaried worker gets paid the hourly wage for
40 hours, no matter what the actual number of hours is. Supply a test
program to test these classes and methods. (Provide toString() for each
classes)
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 23
Interface
• Declares a set of methods and their signatures
• Unlike class
– Provides no implementation
– Cannot instantiate
– Does not contain any constructor
Ex)
public interfaceWorker {
double computePay(int hours);
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 24
implement for interface
public class HourlyWorker implements Worker {
private double rate;
public HourlyWorker(double rate) {
this.rate = rate;
}
public double computePay(int hours) {
if (hours > 40)
return (hours – 40) * rate * 1.5 + 40 * rate;
else
return hours * rate;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 25
implement for interface cont.
public class SalariedWorker implements Worker {
private int rate;
public SalariedWorker(int rate) {
this.rate = rate;
}
public double computePay(int hours) {
if (hours > 40)
return 40 * rate;
else
return hours * rate;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 26
implement for interface cont.
public class Main {
public static void main(String[] args) {
Worker worker1 = new Worker(); // Error
Worker worker2 = new HourlyWorker(7.5);
Worker worker3 = new SalariedWorker(10);
System.out.println("worker2: " + worker2.computePay(40));
System.out.println("worker3: " + worker3.computePay(80));
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 27
implement for interface cont.
public class SomeClass {
public void howMuch(Worker worker) {
System.out.println("You earn " + worker2.computePay(40));
}
}
// “You earn 300” will printed for worker2
// “You earn 400” will printed for worker3
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 28
Implementing multiple interfaces
• A class can implement multiple interfaces– Cannot inherit multiple superclasses
Ex)
public interface AAA {
public int a();
}
public interface BBB {
public int b();
}
public class CCC implements AAA,BBB {
public int a() {…};
public int b() {…};
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 29
Exception handling
• An exception is an event to indicate an error
Throw
Catch
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 30
Types of exceptions
• Checked exception
– Checked at compile-time
– All subclasses of Exception except RuntimeException
• Unchecked Exception
– Not checked at compile-time rather checked at runtime
– Subclasses of RuntimeException
Ex) ArithmeticException
Int a = 50 / 0;
Ex) NullPotinerException
String s = null;
System.out.println(s.length);
Ex) ArrayIndexOutofBoundsException
Int a[] = new int [5];
a[10] = 50;
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 31
Throwing exception
public class BankAccount {
public void withdraw(double amount) {
if (amount > balance) {
//
// now what?
}
balance = balance – amount;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 32
Throwing exception cont.
public class BankAccount {
public void withdraw(double amount) {
if (amount > balance) {
IllegalArgumentException exception = new IllegalArgum
entException("Amount exceeds balance");
throw exception;
}
balance = balance – amount;
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 33
Catching exception
public static void main(String[] args) {
BankAccount acct = new BankAccount(100);
try {
acct.withdraw(200);
} catch (IllegalArgumentException ex) {
System.out.println("Withdraw failed.");
//or ex.printStackTrace();
}
}
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 34
Exercise 3
• Modify the BankAccount class to throw IllegalArgumentException
when the account is constructed with a negative balance, when a
negative amount is deposited, or when an amount that is not
between 0 and the current balance is withdrawn. Write a test
program that causes all three exceptions to occur and that
catches them all
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 35
ArrayList
• An ArrayList is a sequence of objects
Ex) Assume that Coin class is already defined
ArrayList coins = new ArrayList();
coins.add(new Coin(0.1,“dime”));
coins.add(new Coin(0.25, “quarter”));
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 36
ArrayList methods
• boolean add(E e)
– Appends the specified element to the end of this list.
• void add(int index, E element)
– Inserts the specified element at the specified position in this list.
• E get(int index)
– Returns the element at the specified position in this list.
• E remove(int index)
– Removes the element at the specified position in this list.
• int size()
– Returns the number of elements in this list.
SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong ([email protected]) 37
Exercise 4
• Implement a class Bank that contains an array list of BankAccount
objects. Support methods,
– public void addAccount(double initialBalance)
– public void deposit(int account, double amount)
– public void withdraw(int account, double amount)
– public double getBalance(int account)
• An account number is simply an index into the array list