˝ – ¿ § —クラブ理念— 2 w ^ s R w u O v U z ™ t G V s ) \ \ q g r ‘ z – ¿ § t v c z ¶ ˝ \ ˘ z \ ˘ t S M o t q m \ q g r ‘ h / p z q ‹ w M z ¶ ˝ z ˝ – ¿ § t ¶ o w 7 T T ^ z ‘ o M h i Z ‰ L ƒ ‘ o M b { – ¿ § p w A L x j z – ¿ § L a o z q Q ¢ – ~ ~ £ q Q t ˙ Z z « p V w › R ‘ “継続は力なり” 競技面 生活面 学習面 w ‰—ƒ‡¿q‘ow§=$˝Lƒb w k‘M¯6tUz.z^w²˝$ w RtSMo2s–¿§ƒw›RO w –¿§UpK²t˝\pK\qfib\q w w q ‘ o K z t U p V O s F O \ q w twqtszO‘™O\q w ~/oe$sCpxsX~X[w^hu\q w Rz‘qq‘oAsqQt˙Z\q w ?˜t²²VtLtROvz–Oa\q w FY‘M\˘›‘z~gw*$\q w q$zob\q w k¢wG~scuOzü²^hu\q£ w ¶6tt˚z«pVOtb\q w $z¶6t0‘uˆ$s˚O\q 国士舘高校サッカー部選手の目標
1
Embed
Java: part I · •The name of the constructor is always the same as the classname •When we do not define a constructor, java generates a default (parameterless) constructor =>
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
System.out.println(p.getName() + " was born on " + p.getBirthdate().format(fmt));
Java implementation hiding(javaclass02)
• Fullname is calculated but we do not know that unless we look at the code
public class Person {private String firstname;private String lastname;…//public getter() method that returns a calculated valuepublic String getFullname() {
return firstname + " " + lastname;}
}
Java method overloading (javaclass03)
• We can have two methods with the same name, provided the argumentsare different
public void setBirthdate(LocalDate birthdate) {
this.birthdate = birthdate;
}
//Overloaded method (same name, different arguments)
public void setBirthdate(int year, int month, int day) {
this.birthdate = LocalDate.of(year, month, day);
}
Java method overloading(javaclass03)
• Different return value is not enough (=> error here)
• The name of the constructor is always the same as the classname
• When we do not define a constructor, java generates a default (parameterless) constructor => we were able to writePerson p = new Person(); //Person() is a constructor
• A constructor is used to initialize an object.
• A constructor is the first method to be called on an object
Java constructor(javaclass04)
public class Person {private String name;private LocalDate birtdate;//When we do not define a constructor, Java generates a default
(empty) constructor//When we define our own constructor, the default constructor does
not existpublic Person(String name, LocalDate birtdate) {
this.name = name;this.birtdate = birtdate;
}
Java constructor(javaclass04)
• Using a constructorpublic static void main(String[] args) {
//Person p = new Person(); // not possible because default constructor does not exist
// When we create a person object, we have to give a name and a birthdate
Person p = new Person("Elvis", LocalDate.of(1935, 1, 8));System.out.println(p.getName() + " was born on " +
p.getBirtdate().toString());}
Java constructor overloading(javaclass05)
• We can call a constructor from within a constructor
public class Person {
public Person(String name) {
this.name = name;
birthdate = LocalDate.now(); // default birthdate
}
//Constructor overloading (same name, different arguments
public Person(String name, LocalDate birthDate) {
this(name); //calls public Person(String name)
this.birthdate = birthDate;
}
Java exceptions
• Exceptions are used to signalize an error
• Exceptions are part of the method signature• This method needs these arguments
• This method gives this return value
• This can go wrong with the method
• An exception cannot be ignored (program simply crashes)
• We can write code to handle the exception( catching an exception)
Java catch exception(javaexception01)
public static void main(String[] args) {
try {
int number = Integer.parseInt(JOptionPane.showInputDialog("Give a number: "));
System.out.println("The number is " + number);
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("This is not a valid number");
}
System.out.println("When an exception is caught, the program continues.");
}
Java throw exception(javaexception02)
public void setBirthdate(LocalDate birthdate) throws IllegalArgumentException {
//"throws" is not necessary in the method declaration( in this case)
// because it a RuntimeExeption. But it is part
// of the documentation of the method => we mention it
if (LocalDate.now().compareTo(birthdate) < 0) throw new IllegalArgumentException("birthdate cannot be after today");
this.birthdate = birthdate;
}
Java throw exception(javaexception02)
• We do not catch the exception= >program crash
Person eve = new Person();
eve.setName("Eve");
eve.setBirthdate(LocalDate.of(2014,12, 31)); // this should throw an Exception
System.out.println(eve.getName() + " was born on " + eve.getBirthdate()); //not executed
Java period (javaexception03)
private class DatePeriod {
private LocalDate start;
private LocalDate end;
public DatePeriod(LocalDate start, LocalDate end) throws IllegalArgumentException{
if (start.compareTo(end) > 0) throw new IllegalArgumentException("Enddate should not be before start date");
this.start = start;
this.end = end;
}
Java BigDecimal(javanumbersandstrings01)
• BigDecimal is used for currency (float is not precise)
JOptionPane.showMessageDialog(null, "This is a valid account");
} else {
JOptionPane.showMessageDialog(null, "This is not a valid account");
}
Java regular expressions(javanumbersandstrings04)//A question mark means the previous character 0 or 1 timesPattern pattern = Pattern.compile("([0-3]?[0-9])/([0-1]?[0-9])/([0-9]{4})");Matcher matcher = pattern.matcher(date);if (matcher.matches()) {
//Because we have used brackets, we can extract the three groups that were surrounded by brackets
int day = Integer.parseInt(matcher.group(1));int month = Integer.parseInt(matcher.group(2));int year = Integer.parseInt(matcher.group(3));System.out.printf("We get the date %02d-%02d-%4d", day, month, year);
} else {
System.out.println("Sorry, no match");
}
Java inheritance(javainherit01)
• Every class in Java ultimately “inherits” from the class Object
• “Inherits” means that it automatically has all the methods from the base class
• So all methods that are defined in the class Object are available in allJava classes:• toString()
• equals()
• getClass()
• hashCode()
Java inheritance(javainherit01)
public class Person /*extends Object */ {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Java inheritance(javainherit02)
• We use inheritance for an “is-a” relation between classes
• An Employee “is a” Person (with a department)
public class Employee extends Person{
private String department;
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
Java call base constructor(javainherit03)
public class Person {
private String name; //inaccessible to any other class
public String getName() {
return name;
}
public Person(String name) {
this.name = name;
}
}
Java call base constructor(javainherit03)
public class Employee extends Person {
private String department;
public String getDepartment() {
return department;
}
public Employee(String name, String department) {
//this.name = name; // name is private in Person => inaccessible
super(name); // calls contructor from Person
this.department = department;
}
}
Java method overriding(javainherit04)
• A subclass can change the implementation of base methods(overriding)
public class Person {
//method overriding
public String toString() {
return "My name is " + name;
}
}
Java polymorphism(javainherit05)
• Different classes => different implementations
public class Person {
//overrides toString() in Object
public String toString() {
return "The name of this person is " + name;
}
}
Java polymorphism(javainherit05)
public class Employee extends Person {
public Employee(String name) {
super(name);
}
//overrides toString() in Person
public String toString() {
return "The name of this employee is " + getName();
}
}
Java polymorphism(javainherit05)
public static void main(String[] args) {
Person[] persons = new Person[2];
persons[0] = new Person("Elvis");
persons[1] = new Employee("Priscilla");
for(Person p: persons) {
//When p is a Person the toString() method from Person is called
//When p is an Employee the toString() method from Employee is called
//==> polymorphism
System.out.println(p);
}
}
Java abstract class(javaabstract01)
• Sometimes we have no idea how to implement a method
Figure
getPerimeter()
Circle
getPerimeter()
Square
getPerimeter()
How can we calculate the perimeter when we do not know what kind of figure it is?
Java abstract class(javaabstract01)
public abstract class Figure { // a class with an abstract method must be abstract
private String name;
public Figure(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract double getPerimeter(); // no implementation
}
Java abstract class (javaabstract01)
public class Circle extends Figure {
private double diameter;
public double getDiameter() {
return diameter;
}
public Circle(String name, double diameter) {
super(name);
this.diameter = diameter;
}
@Override
public double getPerimeter() {
return diameter * Math.PI;
}
}
Java abstract class(javaabstract01)
• Now we can handle squares and circles together as figures
public static void main(String[] args) {
Figure[] figures = new Figure[2];
figures[0] = new Square("Square One", 10);
figures[1] = new Circle("Circle One", 5);
for(Figure f : figures) {
System.out.printf("The perimeter of %s is %.2f\n", f.getName(), f.getPerimeter());
}
Java abstract class(javaabstract01)
• If we want to access the properties which are specific for squares or circles, we needcasting (and type checking)
for(Figure f : figures) {
if (f instanceof Square) {
double side = ((Square)f).getSide();
System.out.printf("The perimeter of %s with side %.2f is %.2f\n", f.getName(), side, f.getPerimeter());
}else {
double diameter = ((Circle)f).getDiameter();
System.out.printf("The perimeter of %s with diameter %.2f is %.2f\n", f.getName(), diameter, f.getPerimeter());
}
}
Java interface(javainterface01)
• Interfaces are super abstract classes => they have no implementation
• Interfaces often describe an ability of a class
• Ability really means that there are certain methods available
• E.g. when something can be located, it must have getXCoordinate() en getYCoordinate() methods
• A class can only inherit from one base class but it can implementmultiple interfaces
Java interface(javainterface01)
public interface Locatable {
int getXCoordinate();
int getYCoordinate();
}
public interface Movable extends Locatable {
void move(int x_dir, int y_dir);
}
Java interface(javainterface01)
public class House implements Locatable {private int x, y;public House(int x, int y) {
this.x = x;this.y = y;
}@Overridepublic int getXCoordinate() {
return x;}@Overridepublic int getYCoordinate() {
return y;}
@Overridepublic String toString(){
return "House";}
}
Java interface(javainterface01)
public class Car implements Movable {private int x, y;public Car(int x, int y) {
this.x = x;this.y = y;
}@Overridepublic int getXCoordinate() {
return x;}@Overridepublic int getYCoordinate() {
return y;}@Overridepublic void move(int x_dir, int y_dir) {
x+= x_dir;y+= y_dir;
}@Overridepublic String toString() {
return "Car";}
}
Java interface(javainterface01)
public static void main(String[] args) {
Locatable[] locatables = new Locatable[3];
Movable[] movables = new Movable[2];
locatables[0] = new House(50, 20);
Car c = new Car(20, 30);
locatables[1] = c;
movables[0] = c;
Person p = new Person(10,10);
locatables[2] = p;
movables[1] = p;
for(Movable m: movables) {
Move(m, 10, 10);
}
printPosition(locatables);
}
Java interface(javainterface01)
• We can write methods that work with locatables or movables
private static void Move (Movable m, int distX, int distY) {
• Collections are classes that can contain multiple objects (compare toan array)
• Java collections are based on interfaces
Java collections: Collection interface
• Collection has the ability to hold a group of elements
• That means the ability to• Add a new element
• Remove an existing element
• Remove all elements (clear)
• Get the number of elements (size)
• Test whether the set is empty
• See whether the collection contains an element or not
• Traverse the elements (iterator)
Java collections(javacollection01)
public static void main(String[] args) {
Collection<String> building = new ArrayList<>();
building.add("Elvis");
if(building.contains("Elvis")) {
System.out.println("Elvis is in the building");
} else {
System.out.println("Elvis has left the building");
}
if (building.isEmpty()) {
System.out.println("The building is empty");
} else {
System.out.println("There is someone in the building");
}
Java iterator(javacollections01)
• An iterator has a method to determine if there is still another element(hasNext()), to advance and get the next element (next()) and to remove the current element (remove())
Iterator<String> it = building.iterator();
while (it.hasNext()) {
String name = it.next();
System.out.println(name);
}
//When a class has an iterator, we can use a for each
for (String s: building) {
System.out.println(s);
}
Java aggregate operations(javacollections02)
• Since Java 8 we can also traverse a set using a Stream and lambda expressions
• Let us say we have an Employee class:
public class Employee {private String name, department;public Employee(String name, String department) {
this.name = name;this.department = department;
}public String getName() {
return name;}public String getDepartment() {
return department;}
}
Java aggregate operations(javacollection02)
• We can traverse the list and print the employees from the accountintdepartment:
Collection<Employee> company = new ArrayList<Employee>();
System.out.println("There is an Elvis impersonator here");
}
Java sets (javacollection04)
• So we have to override the equals() method:@Overridepublic boolean equals(Object o) {
boolean equal = false;if (o instanceof Employee) {
Employee e = (Employee)o;equal = this.getName().equals(e.getName());
}return equal;
}
Java sets (javacollection04)
• But we use a HashSet so we also have to override the method tocalculate the hashcode.
• The hashcode is used to determine in which “bucket” the item shouldbe placed. In this case we use the hashCode from the name string
@Override
public int hashCode() {
return name.hashCode();
}
Java sets(javacollection4)
• There are different classes that implement Set:• HashSet : items are placed in buckets based on their hashCode (random
order) => very quick
• TreeSet: items are placed using a B-tree (ordered by value) => slower thanHashSet because of traversing the B-tree
• LinkedHashSet: hashtable with a linked list to order the items (insertion order) => almost as fast as a HashSet
Java list interface
• A list is an ordered collection (position capabilities)
• A list can contain the non-unique values
• A list has to ability to• Get an element by position in the list
• Set an element by an existing position in the list
• Get the position of the first occurence of an element
• Iterate over the list in reverse order (using a ListIterator instead of an Iterator) or starting from a certain position
Java list (javacollection05)
List<String> items = new ArrayList<>();items.add("Elvis"); // position 0items.add("Colonel Parker"); // position 1items.set(1, "Dries Van Kuijk"); // replace element 1items.add("Vernon");int index = items.indexOf("Elvis");System.out.println("Elvis is on position " + index);items.remove(1);String name = items.get(1); //Vernon is shifted to position 1System.out.println("On position 1 we have " + name);
Java ListIterator(javacollection05)
• Using a ListIterator we can iterate backward
ListIterator<String> it = items.listIterator(items.size()); //start at endwhile (it.hasPrevious()) {
System.out.println(it.previous());}
• Or using a for-loop
for(ListIterator<String> it = items.listIterator(items.size()); it.hasPrevious();) {
System.out.println(it.previous());
}
Java Map interface
• A Map is not a Collection (Collection contains single values)
• A Map holds key-value pairs
• The keys must be unique
• A key is connected to one value
• A map has to ability to• Put new key-value pairs in the map
• Get a value based on a key
• Check whether a key exists or not
• Check whether a value exists or not
Java Map (javacollection06)
String[] words = {"one", "two", "one", "three", "three", "one"};
Map<String, Integer> frequency = new HashMap<>();
for(String word: words) {
Integer freq = frequency.get(word);
if (freq == null) {
freq = 1;
} else {
freq = freq + 1;
}
frequency.put(word, freq);
}
System.out.println(frequency);
Java Swing
• The Swing classes are used to create a graphical user interface
• The class that represents the main window must be a JFrame. (or inherit from JFrame)
• JFrame contains a constructor with which we can set the title of the window
• A window also needs a size (setSize(Dimension))
• We also have to define what should happen when the user closes the window => exit the application
Java Swing(javaswing01)
public class Main{
public static void main(String[] args) {
JFrame w = new JFrame("First GUI app");
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(new Dimension(300, 300));
w.setVisible(true);
}
}
Java swing(javaswing02)
• We start with a frame
JFrame w = new JFrame("First GUI app");
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(new Dimension(600, 300));
w.setLocationRelativeTo(null); // center on screen