connect friend class

public class PersonDemo 
{
    public static void main(String[] args)
    {
        Person sara = new Person("Sara", "sara.jpg", 10, 200);
        Person chenghan = new Person("Cheng-Han", "cheng-han.png", 300, 0);
        Person cay = new Person("Cay", "cay.gif", 250, 180);
    }
}

// Bluej project: lesson3/friends4
public class Person
{
    private String name;
    private String friends;
    private int x;
    private int y;
    

    public Person (String aName, String pictureName, int xCoord, int yCoord)
    {
        name = aName;
        friends = "";
        x = xCoord;
        y = yCoord;
        Picture picture = new Picture(pictureName);
        picture.translate(xCoord, yCoord);
        picture.draw();
    }
    
    public void addFriend(Person friend) 
    {
        friends = friends + friend.name + " ";
        SmallCircle circle = new SmallCircle(x, y);
        circle.fill();
        Line line = new Line(x, y, friend.x, friend.y);
        line.draw();
    }
    
    public void unfriend(Person nonFriend)
    {
        friends = friends.replace(nonFriend.name + " ", "");
    }
    
    public String getFriends() 
    {
        return friends;
    }
}

The this Reference

public double drive(double distance)
{
  this.mimlesDriven = this.milesDriven + distance
}
public Person (String name, String pictureName, int x, int y)
{
    this.name = name;
    this.friends = "";
    this.x = x;
    this.y = y;
    Picture picture = new Picture(pictureName);
    picture.translate(x, y);
    picture.draw();
}

draw picture class

public class PersonDemo 
{
    public static void main(String[] args)
    {
        Person sara = new Person("Sara", "sara.jpg", 10, 200);
        Person chenghan = new Person("Cheng-Han", "cheng-han.png", 300, 0);
        Person cay = new Person("Cay", "cay.gif", 250, 180);
    }
}
public class Person
{
    private String name;
    private String friends;
    
    public Person (String aName, String pictureName, int xCoord, int yCoord)
    {
        name = aName;
        friends = "";
        Picture picture = new Picture(pictureName);
        picture.translate(xCoord, yCoord);
        picture.draw();
    }
    
    public void addFriend(Person friend) 
    {
        friends = friends + friend.name + " ";
    }
    
    public void unfriend(Person nonFriend)
    {
        friends = friends.replace(nonFriend.name + " ", "");
    }
    
    public String getFriends() 
    {
        return friends;
    }
}

GasInTank

instance variable stay long, but local variable only stay short term.

public class CarTester
{
    public static void main(String[] args)
    {
        Car car = new Car();

        // TODO: Add 20 gallons and drive 100 miles
        car.addGas(20);
        car.drive(100);
        
        // TODO: Print actual and expected gas level
        System.out.println("Expected:18");
        System.out.println(car.getGasInTank());
    }
}
public class Car
{
    private double milesDriven;
    private double gasInTank;
    private double milesPerGallon;

    public Car()
    {
        milesDriven = 0;
        gasInTank = 0;
        milesPerGallon = 50;
    }

    /**
       Drives this car by a given distance.
       @param distance the distance to drive
    */
    public void drive(double distance)
    {
        milesDriven = milesDriven + distance;
        double gasConsumed = distance / milesPerGallon;
        gasInTank = gasInTank - gasConsumed;
    }

    public void addGas(double amount)
    {
        gasInTank = gasInTank + amount;
    }
    
    /**
       Gets the current mileage of this car.
       @return the total number of miles driven
    */
    public double getMilesDriven()
    {
        return milesDriven;
    }

    /**
       Gets the current amount of gas in the tank of this car.
       @return the current gas level
    */
    public double getGasInTank()
    {
        return gasInTank;
    }
}

test programming

public class test
{
    public static void main(String[] args)
    {
      Rectangle box = new Rectangle(45, 90, 60, 90);
      box.grow(20, 20);
      system.out.println(box.getX());
      system.out.println("exected: 25");
      system.out.println(box.getY());
      system.out.println("exected: 70");
    }
}
Rectangle frontFace = new Rectangle(20, 30 ,100, 40);
        Line leftLine = new Line(20, 30, 50, 10);
        Line topLine = new Line(50, 10, 150, 10);
        Line middleLine = new Line(120, 30, 150, 10);
        Line rightLine = new Line(150, 10, 150, 50);
        Line bottomLine = new Line(120, 70, 150, 50);

        frontFace.draw();
        leftLine.draw();
        topLine.draw();
        middleLine.draw();
        rightLine.draw();
        bottomLine.draw();
      box.setColor(new Color(255, 0, 0));
      box.draw();
      box2.setColor(new Color(0, 255, 0));
      box2.fill()

Object oriented programming

java put name before the variable name.

public class test
{
    public static void main(String[] args)
    {
        Picture rocket = new Picture("mariner4.jpg");
        rocket.translate(200, 200);
        rocket.draw();
        Picture planet = new Picture("mars.gif");
        planet.grow(-50, -50);
        planet.draw();
    }
}
public class test
{
    public static void main(String[] args)
    {
        Day birthday = new Day(1951, 5, 26);
        Day lastDay = new Day(2012, 5, 26);
        int daysAlive = lastDay.daysFrom(birthday);
        System.out.println(daysAlive);
    }
}

variable can vary and assignment has no type.

int numberOfPixels = object.methodname(arguments)

public class test
{
    public static void main(String[] args)
    {
        Rectangle box = new Rectangle(60, 90, 20, 30);
        Rectangle box2 = new Rectangle(80, 120, 20, 30);
        box.draw();
        box2.draw();
    }
}
public class test
{
    public static void main(String[] args)
    {
        String river = "Mississippi";
        int numberOfLetters = river.length();
        System.out.println(numberOfLetters);
    }
}

replace method

public class test
{
    public static void main(String[] args)
    {
        String river = "Mississippi";
        String result = river.replaceAll("i","x");
        System.out.println(result);
    }
}

cut space with trim()

String messyString = "Hello, Space!";
        messyString.trim()

AccessorとMutator:「Accessor=アクセスするヤツ」、「Mutator=mutate(訳すと変化させる)」
An accessor method is used to return the value of a private field.
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word “set” to the start of the method name.

Implement test program, set actual result and expected result.

Test program

public class test
{
    public static void main(String[] args)
    {
        System.out.println("Hello\nWorld!");
    }
}

print and println

public class test
{
    public static void main(String[] args)
    {
        System.out.print(3);
        System.out.println(4 + 5);
    }
}

compile error

public class test
{
    public static void main(String[] args)
    {
        System.ouch.println(4 + 5);
    }
}

Java 構文5

HashMap

import java.util.*;

public class MyApp{
  public static void main(String[] args){
      HashMap<String, Integer> sales = new HashMap<>();

      sales.put("tom", 10);
      sales.put("john", 20);
      sales.put("mason", 30);

          System.out.println(sales.get("tom"));
          System.out.println(sales.size());

          for (Map.Entry<String, Integer> sale: sales.entrySet()){
            System.out.println(sale.getKey() + ":" + sale.getValue());
          }
    }
}

StreamAPI

import java.util.*;

public class MyApp{
  public static void main(String[] args){

      List<Integer> sales = new ArrayList<>(Arrays.asList(12, 30, 22, 4, 9));
      sales
       .stream()
       // 中間処理
       .filter(e -> e % 3 == 0)
       // 終端処理
       .map(e -> "(" + e+ ")")
       .forEach(System.out::println);
    }
}

LocalDateTime

import java.time.*;
import java.time.format.DateTimeFormatter;

public class MyApp{
  public static void main(String[] args){
      LocalDateTime d = LocalDateTime.now();
      // LocalDateTime d = LocalDateTime.of(2017, 1, 1, 10, 10, 10);
      // LocalDateTime d = LocalDateTime.parse("2016-12-12T10:10:10");

      System.out.println(d.getYear());
      System.out.println(d.getMonth());
      System.out.println(d.getMonth().getValue());

      System.out.println(d.plusMonths(2).minusDays(3));
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy!MM!dd!");
      System.out.println(d.format(dtf));
    }
}

Java 構文4

例外

// 例外処理
class MyException extends Exception {
  public MyException(String s){
    super(s);
  }
}

public class MyApp{

  public static void div(int a, int b){
    try {
      if (b < 0){
        throw new MyException("not minus!");
      }
      System.out.println(a / b);
    } catch (ArithmeticException e){
      System.err.println(e.getMessage());
    } catch (MyException e){
      System.err.println(e.getMessage());
    } finally{
      System.out.println(" -- end -- ");
    }
  }
  public static void main(String[] args){
    div(3, 0);
    div(5, -2);
  }
}

ラッパークラス

public class MyApp{
  public static void main(String[] args){
    // Integer i = new Integer(32);
    // int n = i.intValue();
    Integer i = 32; // auto boxing
    i = null;
    int n = i; // auto unboxing
    
    System.out.println();
  }
}

generics:型の汎用化

class MyData<T> {
  public void getThree(T x){
    System.out.println(x);
    System.out.println(x);
    System.out.println(x);
  }
}

public class MyApp{
  public static void main(String[] args){
    // MyInteger mi = new MyInteger();
    // mi.getThree(55);
    MyData<Integer> i = new MyData<>();
    i.getThree(32);
    MyData<String> s = new MyData<>();
    s.getThree("hello");
  }
}

Thread処理:

class MyRunnable implements Runnable{
  @Override
  public void run(){
    for (int i= 0; i < 500; i++){
      System.out.print('*');
    }
  }
}

public class MyApp{
  public static void main(String[] args){
    MyRunnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start();

    for (int i= 0; i < 500; i++){
      System.out.print('.');
    }
  }
}

無名クラス

public class MyApp{
  public static void main(String[] args){
    // MyRunnable r = new MyRunnable();
    // Thread t = new Thread(r);
    // t.start();
    new Thread(new Runnable(){
      @Override
      public void run(){
        for (int i= 0; i < 500; i++){
          System.out.print('*');
        }
      }
    }).start(); // 無名クラス

    for (int i= 0; i < 500; i++){
      System.out.print('.');
    }
  }
}

Stringクラス

public class MyApp{
  public static void main(String[] args){
      String s = "abcdef";
      System.out.print(s.length());
      System.out.print(s.substring(2, 5));
      System.out.print(s.replaceAll("ab","AB"));

      String s1 = "ab";
      String s2 = "ab";

      if (s1.equals(s2)){
        System.out.print("same!");
      }

      if (s1 == s2){
        System.out.print("same!same!");
      }
    }
}

printfメソッド

public class MyApp{
  public static void main(String[] args){
    int score=50;
    double height=165.8;
    String name ="yoshimoto";

      System.out.printf("name: %s, score: %d, height: %f\n", name, score, height);
      System.out.printf("name: %-10s, score: %10d, height: %5.2f\n", name, score, height);

      String s = String.format("name: %10s, score: %-10d, height: %5.2f\n", name, score, height);
      System.out.println(s);
    }
}

Math, randomクラス

import java.util.Random;

public class MyApp{
  public static void main(String[] args){
      double d = 53.234;
      System.out.println(Math.ceil(d));
      System.out.println(Math.floor(d));
      System.out.println(Math.round(d));
      System.out.println(Math.PI);

      Random r = new Random();
      System.out.println(r.nextDouble()); // 0-1
      System.out.println(r.nextInt(100)); // 0-1
      System.out.println(r.nextBoolean()); // 0-1
    }
}

ArrayList

import java.util.*;

public class MyApp{
  public static void main(String[] args){
      List sales = new ArrayList<>();

      sales.add(10);
      sales.add(20);
      sales.add(30);

      for (int i = 0; i < sales.size(); i++){
        System.out.println(sales.get(i));
      }

      sales.set(0, 100);
      sales.remove(2);

      for (Integer sale: sales){
        System.out.println(sale);
      }

    }
}

Hash.set

import java.util.*;

public class MyApp{
  public static void main(String[] args){
      HashSet sales = new HashSet<>();

      sales.add(10);
      sales.add(20);
      sales.add(30);
      sales.add(10);

        System.out.println(sales.size());

        for (Integer sale: sales){
          System.out.println(sale);
        }
        sales.remove(30);
        for (Integer sale: sales){
          System.out.println(sale);
        }
    }
}

Java 構文3

getter, setter

class User {
  private String name;
  private int score;

  public User(String name, int score){
    this.name = name;
    this.score = score;
  }

  public int getScore(){ //getter
    return this.score;
  }

  public void setScore(int score){
    if (score > 0) {
    this.score = score;
   }
  }

}

public class MyApp{

  public static void main(String[] args){
    User tom = new User("tom", 65); // instance
    tom.setScore(85);
    tom.setScore(-22);
    System.out.println(tom.getScore());
  }
}

static:インスタンス化しなくても、クラスから直接扱えるフィールドやメソッドを定義できます。

class User {
  private String name;
  private static int count = 0;

  public User(String name){
    this.name = name;
    User.count++;
  }

  public static void getInfo(){
    System.out.println("# of instances: " + User.count);
  }

}

public class MyApp{

  public static void main(String[] args){
    User.getInfo();
    User tom = new User("tom");
    User.getInfo();
  }
}

initializer

class User {
  private String name;
  private static int count; //クラス変数

  static {
    User.count = 0;
    System.out.println("static initializer");
  }

  {
    System.out.println("Instance initializer");
  }

  public User(String name){
    this.name = name;
    User.count++;
    System.out.println("constructor initializer");
  }

  public static void getInfo(){
    System.out.println("# of instances: " + User.count);
  }

}

変更できないfinal修飾子

// final 変更できない

final class User {
  protected String name;
  private static final double VERSION = 1.1;

  public User(String name){
    this.name = name;
    User.VERSION = 1.2;
  }

  public final void sayHi(){
    System.out.println("hi! " + this.name);
  }
}

class AdminUser extends User {
  public AdminUser(String name){
    super(name);
  }

  @override
  public void sayHi(){
    System.out.println("[Admin]hi!" + this.name);
  }
}

public class MyApp{

  public static void main(String[] args){
    User tom = new User("tom");
  }
}

抽象クラス

//抽象クラス -> 具象クラス

abstract class User {
  public abstract void sayHi();
}

class JapaneseUser extends User {
  @Override
  public void sayHi(){
    System.out.println("こんにちは!");
  }
}

class AmericanUser extends User {
  @Override
  public void sayHi(){
    System.out.println("hi!");
  }
}

public class MyApp{

  public static void main(String[] args){
    AmericanUser tom = new AmericanUser();
    JapaneseUser aki = new JapaneseUser();
    tom.sayHi();
    aki.sayHi();
  }
}

interface

//interface

interface Printable {
  //定数、
double VERSION = 1.2;
  //抽象
  void print();
 // default method
 public default void getInfo(){
   System.out.println("I/F ver. " + Printable.VERSION);
 }
 // static
}


class User implements Printable {
  @Override
  public void print(){
    System.out.println("Now printing user prifile...");
  }

}

public class MyApp{

  public static void main(String[] args){
    User tom = new User();
    tom.print();
    tom.getInfo();
  }
}

列挙型とordinal()

// 列挙型
enum Result {
  SUCCESS,
  ERROR,
}

public class MyApp{

  public static void main(String[] args){
    Result res;

    res = Result.ERROR;

    switch (res){
      case SUCCESS:
      System.out.println("OK!");
      System.out.println(res.ordinal());
      break;
      case ERROR:
      System.out.println("NG!");
      System.out.println(res.ordinal());
      break;
    }

  }
}

Java packageの書き方

クラス

class User {
  String name = "Me"; // field

  void sayHi(){
    System.out.println("hi!");
  }
}

public class MyApp{

  public static void main(String[] args){

    User tom;
    tom = new User(); // instance
    System.out.println(tom.name);
    tom.sayHi();
  }
}

コンストラクター:クラスの初期化

class User {
  String name;

  // constructor
  User(String name){
    this.name = name;
  }

  // User(){
  //   this.name = "me";
  // }

  User(){
    this("me!");
  }

  void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

public class MyApp{

  public static void main(String[] args){

    User tom;
    tom = new User(); // instance
    System.out.println(tom.name);
    tom.sayHi();
  }
}

クラスの継承とoverride

class User {
  String name;

  User(String name){
    this.name = name;
  }

  void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

class AdminUser extends User {
  AdminUser(String name){
    super(name);
  }
  void sayHello(){
    System.out.println("hello!" + this.name);
  }

  // override
  @Override
  void sayHi(){
    System.out.println("[admin] hi!" + this.name);
  }

}

public class MyApp{
  public static void main(String[] args){

    User tom = new User("tom"); // instance
    System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob"); // instance
    System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }
}

public:アクセス可
private:同じクラスならアクセス可能
protected:同じパッケージのみ

パッケージ化
com/hpscript/myapp/MyApp.java

package com.hpscript.myapp;
import com.hpscript.myapp.model.User;
import com.hpscript.myapp.model.AdminUser;
// import hpscript.myapp.model.*;

public class MyApp{
  public static void main(String[] args){

    User tom = new User("tom"); // instance
    // System.out.println(tom.name);
    tom.sayHi();

    AdminUser bob = new AdminUser("bob"); // instance
    // System.out.println(bob.name);
    bob.sayHi();
    bob.sayHello();
  }
}

com/hpscript/myapp/model/User.java

package com.hpscript.myapp.model;

public class User {
  protected String name;

  public User(String name){
    this.name = name;
  }

  public void sayHi(){
    System.out.println("hi!" + this.name);
  }
}

com/hpscript/myapp/model/AdminUser.java

package com.hpscript.myapp.model;

public class AdminUser extends User {
  public AdminUser(String name){
    super(name);
  }
  public void sayHello(){
    System.out.println("hello!" + this.name);
  }

  // override
  @Override
  public void sayHi(){
    System.out.println("[admin] hi!" + this.name);
  }

}