2015年9月30日 星期三

Comparator 的用法

Comparator 的用法:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorDemo {
    public static void main(String[] args){
    
        List<Student> studentList = new ArrayList<>(3);
        Comparator<Student> sortName = new StudentSortName();
        Comparator<Student> sortGpa = new StudentSortGpa();
        
        studentList.add(new Student("Thomas Jefferson", 1111, 3.8));
        studentList.add(new Student("John Adams", 2222, 3.9));
        studentList.add(new Student("George Washington", 3333, 3.4));
        
        Collections.sort(studentList, sortName);
        for (Student student : studentList){
            System.out.println(student.getName());
        }
         Collections.sort(studentList, sortGpa);
        for (Student student : studentList){
            System.out.println(student.getGpa());
        }
    }
}

public class Student {
private String name;
    private long id = 0;
    private double gpa = 0;
            
    public Student(String name, long id, double gpa) {
        this.name = name;
        this.id = id;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }

    public double getGpa() {
        return gpa;
    }
}

import java.util.Comparator;

public class StudentSortName implements Comparator<Student> {

    public StudentSortName() {
    }

    @Override
    public int compare(Student o1, Student o2) {
        int result = o1.getName().compareTo(o2.getName());
        if (result != 0){return result;}
        else { return 0;}
    }
}

import java.util.Comparator;

public class StudentSortGpa implements Comparator<Student> {

    public StudentSortGpa() {
    }

    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getGpa() < o2.getGpa()){return 1;}
        else if (o1.getGpa() > o2.getGpa()){ return -1;}
        else {return 0;}
    }
}

Comparable 的用法

Comparable 的用法:
public class ComparableStudent implements Comparable<ComparableStudent>{
    private String name;
    private long id = 0;
    private double gpa = 0.0;

    public ComparableStudent(String name, long id, double gpa) {
        this.name = name;
        this.id = id;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }
        
    @Override
    public int compareTo(ComparableStudent o) {
        int result = this.name.compareTo(o.getName());
        if (result > 0){return 1;}
        else if (result < 0){return -1;}
        else {return 0;}
    }
}

Demo 程式:
import java.util.Set;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args){
        Set<ComparableStudent> studentList = new TreeSet<>();
        
        studentList.add(new ComparableStudent("Thomas Jefferson", 1111, 3.8));
        studentList.add(new ComparableStudent("John Adams", 2222, 3.9));
        studentList.add(new ComparableStudent("George Washington", 3333, 3.4));
         
         for (ComparableStudent student : studentList){
             System.out.println(student.getName());
         }
    }
}

Queue 的應用


import java.util.ArrayDeque;
import java.util.Deque;

public class NewClass {
    public static void main(String[] args){
    
        Deque<String> stack = new ArrayDeque<>();
        stack.push("One");
        stack.push("Two");
        stack.push("Three");
        
        int size = stack.size() -1;
        while(size >= 0){
            System.out.println(stack.pop());
        }
    }
}

Map 應用


import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapDemo {
    public static void main(String[] args){
    
        Map<String, String> shirtList = new TreeMap<>();
        shirtList.put("S001", "Blue Shirt");
        shirtList.put("S002", "Black Shirt");
        shirtList.put("S003", "Gray Shirt");
        
        Set<String> keys = shirtList.keySet();
        System.out.println("====== Shirt List ======");
        for (String key : keys){
            System.out.println("Part#: " + key + " " 
                               + shirtList.get(key));
        } 
    }
}

Set 應用

某家公司的面試題目:
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;

public class SetDemo {
    public static void main(String[] args){
    
        Set<Integer> num = new TreeSet<>();
        Scanner scanner = new Scanner(System.in);
        Integer[] b = new Integer[3];
        for (int i = 0; i < 3 ;  i++){
            System.out.print("Please the eage's length: ");
            num.add(scanner.nextInt());
        }
        num.toArray(b);
        if (b[2] < (b[0]+b[1])){
        switch (num.size()){
            case 1: 
                System.out.println("正三角形");
                break;
            case 2:
                System.out.println("等腰三角形");
                break;
            case 3:
                if (triangle(b)){
                    System.out.println("直角三角形");
                } else {
                    System.out.println("其他種類三角形");
                }
        }
        } else {
             System.out.println("無法構成三角形");
        }
    }

    private static boolean triangle(Integer[] b) {
        if ((b[2] * b[2]) == (b[0]*b[0] + b[1]*b[1])){
          return true;
        } else {
            return false;
        }
    }
}


2015年9月23日 星期三

Boxing & UnBoxing

AutoBoxing 與 Auto Unboxing:
public class AutoBox {
    public static void main(String[] args){
    
        Integer intObject = new Integer(1);
        int intPrimitive = 2;
        
        Integer tempInteger;
        int tempPrimitive;
        
        tempInteger = new Integer(intPrimitive);
        tempPrimitive = intObject.intValue();
        
        tempInteger = intPrimitive;  //Auto Boxing
        tempPrimitive = intObject; // Auto Unboxing
    }
}

收集器:ArrayList & List

Collection 利用 Generic 來實作的好處:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
    public static void main(String[] args){
    
        List partList = new ArrayList<>();
        partList.add(new Integer(1111));
        partList.add(new Integer(2222));
        partList.add(new Integer(3333));
        partList.add("Hello World");  //Compile Error : Not Integer
        
        // 利用 Iterator 來遍訪 ArrayList 內的 elements 
        Iterator elements = partList.iterator();  
        while (elements.hasNext()){
            Integer partNumberObject = elements.next();
            int partNumber = partNumberObject.intValue();
            
            System.out.println("Part Number: " + partNumber);
        }
    }
}

Java 泛型概念

泛型的功能:
public class Shirt {
   private int shirtID = 0;

    public int getShirtID() {
        return shirtID;
    }

    public void setShirtID(int shirtID) {
        this.shirtID = shirtID;
    } 
}

public class CacheAny {
    private T t;
    public void add(T t){
        this.t = t;
    }
    public T get(){
        return this.t;
    }
}

public class Demo {
    public static void main(String[] args){
        CacheAny myMessages = new CacheAny<>();
        myMessages.add("This is my Shirt!");
        System.out.println(myMessages.get().toString());
        
        CacheAny myShirt = new CacheAny<>();
        myShirt.add(new Shirt());
        myShirt.get().setShirtID(123456);
        System.out.println("Shirt ID :" + myShirt.get().getShirtID());
    }
}

Composition Implementation

Composition 實作範例:
public interface Car {
    public void start();
}

public abstract class BasicCar {
    public abstract void start();
}

public class Diesel extends BasicCar{
    public void start(){
        System.out.println("Diesel Start....");
    }
}

public class Mobile extends BasicCar{
    public void ignite(){
        System.out.println("Power turn on ...");
    }

    @Override
    public void start() {
        this.ignite();
    }
}

public class Hybrid  implements Car{
    private Diesel die = new Diesel();
    private Mobile m1 = new Mobile();
    
    public void start(){
        die.start();
        m1.ignite();
    }   
}

public class Racing extends Hybrid{
    public void start(){
        super.start();
        System.out.println("Engine is starting.....");
    }
}

public class Demo {
    public static void main(String[] args){
    
        Racing r1 = new Racing();
        r1.start();
    }
}

2015年9月21日 星期一

Java 介面的繼承


public interface Boats {
    public void launch();
}

public interface MotorizedBoat extends Boats{
    public void start();
}

public interface Car {
    public void start();
}

public class BasicCar implements Car{

    @Override
    public void start() {
        Engine e1 = new Engine(){
            public String start(){
                return ("Engine is :" + start());
            }
        };
    }

    private static class Engine {
        public String start(){
            return "Starting ....";
        }
    }  
}

public class AmphibiousCar extends BasicCar implements MotorizedBoat , java.io.Serializable{

    @Override
    public void launch() {
        System.out.println("要行駛了....");
    }   
}

Java 介面的用法

最簡單的介面宣告:
public interface EletronicDevice {
    public void turnOn();
    public void turnOff();
}

使用方式:
public class Television implements EletronicDevice{

    @Override
    public void turnOn() {
        System.out.println("電視機開啟中...");
        initializeScreen();
    }

    @Override
    public void turnOff() {
        initializeScreen();
        System.out.println("電視機關閉中...");
    }
    
    public void changeChannel(int channel){
        System.out.printf("切換至第 %d 台", channel);
    }
    
    private void initializeScreen(){
        System.out.println("清除螢幕視窗....");
    }
}

執行方式:
public class Demo {
    public static void main(String[] args){
        
        EletronicDevice ed = new Television();
        ed.turnOn();

        //介面與類別相同的功能:casting
        ((Television)ed).changeChannel(2); 

        ed.turnOff();
        String s = ed.toString();
        System.out.println(s);
    }
}

巢狀式類別

內部類別示範:
public class Car {

    private boolean running = false;
    private Engine engine = new Engine();

    private class Engine {
        public void start(){
            running = true;
            System.out.println("引擎起動中....");
        }
    }
    
    public void start(){
        engine.start();
        System.out.println("汽車狀態: 準備行駛.....");
    }
}

public class Demo {
    public static void main(String[] args){
        Car c1 = new Car();
        c1.start();
    
    }
}

暱名內部類別示範:
public class CarBrand {

    //建立一個內部有暱名類別的物件
    public LandRover l1 = new LandRover(){

        @Override
        public String toString() {
            return ("Land Rover : " + l1.getBrand1());
        }    
    }; //注意節尾的結束符號
            
    // 這是一般的內部類別用法
    private class LandRover {
        private String brand1 = "Defender !";
        public String getBrand1(){
            return brand1;
        }
    }
}

public class Demo {
    public static void main(String[] args){
        CarBrand c1 = new CarBrand();
        System.out.println(c1.l1);
    }
}

Singleton Design Pattern 的範例

Singleton Design Pattern 的類別,只能實例化一次:
public class Husband {

  private static final Husband yourlover = new Husband();
  private static String name = "Peter" ;
  
  private Husband(){}

  public static Husband getYourLover(){
      System.out.println("Your Husband: " + name);
    return yourlover;
  }
} 

public class Demo {
    public static void main(String[] args){
        Husband.getYourLover();
    }
}

2015年9月19日 星期六

利用 Eclipse 來寫 Java EE 程式


  1. http://pclevin.blogspot.tw/2014/08/javaservlet-hello-world-example.html

  2. http://www.dotblogs.com.tw/alantsai/archive/2013/09/28/servlet-helloworld.aspx

  3. http://xml-nchu.blogspot.tw/2012/10/java-servlet.html

良葛格寫的 Java EE


  1. http://www.codedata.com.tw/java/java-tutorial-the-3rd-class-3-servlet-jsp/

  2. http://openhome.cc/Gossip/ServletJSP/

  3. http://www.slideshare.net/JustinSDK/servlet-jsp-1-web

打包成 war 的方式

  1. http://shuyangyang.blog.51cto.com/1685768/1125131

掌握 Java EE 技術


  1. http://liumh.blog.51cto.com/1388196/504019

2015年9月18日 星期五

Enum 使用方式

Java 的 Enum:
public enum PowerState {
   OFF("This System is off"),
    ON("This System is on"),
    SUSPEND("This System is Suspend");
    
    private String description;
    
    private PowerState(String d){
        description = d;
    }
    public String getDescription(){
        return this.description;
    }
}

測試一下:
public class Computer {

    void setState(PowerState powerState) {
    
        switch(powerState){
            case OFF:
                System.out.println(powerState.getDescription());
                break;
            case ON:
                System.out.println(powerState.getDescription());
                break;
            case SUSPEND:
                System.out.println(powerState.getDescription());
                break;
        }
    }  
}

public class Demo {
    public static void main(String[] args){
    
        Computer comp = new Computer();
    
        comp.setState(PowerState.OFF);
        
    }
}

物件的比較


物件的比較,原則上必須 Override Object 物件內的 equals() 方法:
public class Employee {
    
    private int empId;
    private String name;
    private String ssn;
    private double salary;

    public Employee(int empId, String name, String ssn, double salary) {
        this.empId = empId;
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }

    @Override
    public boolean equals(Object obj) {
        boolean result = false;
        
        if ((obj != null) && (obj instanceof Employee)){
            Employee e = (Employee)obj;
            if ((e.empId == this.empId) &&
                    (e.name.equals(this.name)) &&
                    (e.ssn.equals(this.ssn)) &&
                    (e.salary == this.salary)){
                    result = true;
            }
        }
        
        return result; 
    }

   //......請參考這一篇程式內容......

}

測試用程式:
public class Demo {
    public static void main(String[] args){
           
        Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
        Employee m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
        Employee es = e;
        Employee es2 = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
        
        if ( e ==  es ){
            System.out.println("1.同一物件");
        }
        
        if ( e.equals(es)){
            System.out.println("1.物件內容相同");
        }
        
        if ( e ==  es2 ){
            System.out.println("2.同一物件");
        }
        
        if ( e.equals(es2)){
            System.out.println("2.物件內容相同");
        }
        
        if ( e ==  m ){
            System.out.println("3.同一物件");
        }
        
        if ( e.equals(m)){
            System.out.println("3.物件內容相同");
        }
    }
}

2015年9月16日 星期三

Polymorphism 用法

Polymorphism (多型)用法:
public class Employee {

    //....參考這一篇內容.....
     protected int calculateStock() {
        return 10;
    }
}

public class Manager extends Employee{

    //....參考這一篇內容.....
    public int calculateStock() {
        return 20;
    }
}

新的類別:
public class EmployeeStackPlan {

    private float stockMultiplier = 1.5f;

    // 使用父類別當引數:
    public int grantStock (Employee e){
        return (int)(stockMultiplier * e.calculateStock());
    }
}

執行的執行:
public class Demo {
    public static void main(String[] args){
    
    Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);    
    Manager m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
    Employee em = new Manager(103, "Williams Tim", "014-87-5679",123_560.54, "Production");

    System.out.println("Stock: " + e.calculateStock());
    System.out.println("Stock: " + m.calculateStock());
    System.out.println("Stock: " + em.calculateStock());
    

Override 用法

Java 的Override 用法:
public class Employee {
    
    private int empId;
    private String name;
    private String ssn;
    private double salary;

    public Employee(int empId, String name, String ssn, double salary) {
        this.empId = empId;
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }

    public String getDetail(){
        return ("Employee ID : " + getEmpId() +
                " Employee Name: " + getName());
    }

    //......一堆 getter & setter ......
}

public class Manager extends Employee{
    
    private String deptName;

    public Manager(int empId, String name, String ssn, double salary, String deptName) {
        super(empId, name, ssn, salary);
        this.deptName = deptName;
    }
    public String getDetail(){
        return (super.getDetail() + 
                " Department: " + getDeptName());
    }
 //......一堆 getter & setter ......
}

public class Demo {
    public static void main(String[] args){
    
        Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
        Manager m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
        System.out.println(e.getDetail());
        System.out.println(m.getDetail());
    }
}

Java 權限修飾詞

Java 權限修飾詞: private、default、protected、public
package demo;

public class Foo {
    private int result = 20;
    protected int getResult(){
        return result;
    }
}

package test;

import demo.Foo;

public class Bar extends Foo{
    private int sum = 10;
    public void reportSum(){
        sum += getResult();
        System.out.println("Sum :" + sum );
    }
}

public class Demo {
    public static void main(String[] args){
    
        Bar abc = new Bar();
        abc.reportSum();
    } 
}

Method 的可變長度引數

方法中,可變長度的引數宣告:
public class Statistics {
    public float average(int... nums){
    
        int sum = 0;
        for (int x : nums){
            sum += x;
        }
        return ((float)sum / nums.length);
    }
}

使用方式:
public class Demo {
    public static void main(String[] args){
    
        Statistics abc = new Statistics();
        int[] nums = {32,67,98,34,76};
        System.out.println("Average: " + abc.average(nums));
    }
}

2015年9月14日 星期一

物件與多型

Java 多型 (Polymorphism) 的使用:
範例:Employee
public class Employee {
    
    private int empId;
    private String name;
    private String ssn;
    private double salary;

    public Employee() {
    }

    public Employee(int empId, String name, String ssn, double salary) {
        this.empId = empId;
        this.name = name;
        this.ssn = ssn;
        this.salary = salary;
    }

    //......一堆 getter 與 setter ......

   public void raiseSalary(double increase){
        salary += increase;
    }

}

Manager 繼承 Employee :
public class Manager extends Employee{
    
    private String deptName;

    public Manager() {
    }

    public Manager(int empId, String name, String ssn, double salary, String deptName) {
        //super();
        super(empId, name, ssn, salary);
        this.deptName = deptName;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }   
}

最後來個大Demo :
public class Demo {
    public static void main(String[] args){
    
        Manager mgr = new Manager(102, "Barbara Jones", "107-99-9078", 109345.67, "Marketing");
        mgr.raiseSalary(10000.00);
        String dept = mgr.getDeptName();
        
        Employee emp = new Manager();
        //錯誤
        //emp.setDeptName("Marketing");
        ((Manager)emp).setDeptName("Marketing");
    }
}

傳值呼叫

Java 傳值方式:Call by Value
針對基本數值:
int x = 3;
int y = x;
// x 將數值直接 copy 給 y

針對物件:
public class Demo {
    public static void main(String[] args){
    
        Employee x = new Employee();
        System.out.println("Salary: " + x.salary);
        foo(x);
        System.out.println("New Salary: " + x.salary);
    }

    // x -> e ,直接 copy 記憶體位址值
    public static void foo(Employee e) {
        //e = new Employee();
        e.setSalary(5000.00);
    }
}

class Employee {
    double salary = 1000.00;

    void setSalary(double d) {
        this.salary = d;
    }  
}

2015年9月11日 星期五

Package & Import 用法

利用 Package 來將專案內的檔案,進行分類:
package com.HR;

public class Employee {

    private String name;
    private int empID;
    private String ssn;
    private double salary;

    public Employee() {
    }

    public Employee(int empID, double salary, String ssn, String name) {
        this.empID = empID;
        this.salary = salary;
        this.ssn = ssn;
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public String getSsn() {
        return ssn;
    }

    public String getName() {
        return name;
    }

    public int getEmpID() {
        return empID;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void setSsn(String ssn) {
        this.ssn = ssn;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmpID(int empID) {
        this.empID = empID;
    }
}

Import 進來上述的 Class :
import com.HR.Employee;

public class Demo {
    public static void main(String[] args){
    
        Employee e1 = new Employee();
    
    }
}

Java 的 String 物件

String 是常見的 Java 字串物件:
public class StringOperations {
    
    public static void main(String[] args) {
       
        String string2 = "World";
        String string3 = "";
        
        string3 = "Hello".concat(string2);
        System.out.println("String3: " + string3);
        
        System.out.println("Length: " + string3.length());
        
        System.out.println("Sub: " + string3.substring(0, 5));
        
        System.out.println("Upper: " + string3.toUpperCase());
    }
}

Java 介面實作與應用

Java 介面宣告方式:
public interface Refuel{
  
    //介面的方法,可視為抽象方法!
    public String doRefuel();
}

修改一下原來的 Sedan 類別
public class Sedan extends Vehicle implements Refuel{

    private char audioClass;
    private double fuelTank;

    Sedan(int wheels, String engineType, double weight, char audio , double fuelTank){
      super(wheels,engineType,weight);
      this.audioClass = audio;
      this.fuelTank = fuelTank;
    }

    //實作抽象方法
     public void ignite(){
       System.out.println("Engine start!");
    }

    //實作介面方的方法
    public String doRefuel(){
      this.fuelTank = 20.00;
      return "Refeuel :" + this.fuelTank;
    }
}

實作 Sedan 類別:
public class Demo {
 public static void main(String[] args){

    Sedan bm = new Sedan(4, "Diesel" , 2231.21 , 'A' , 0.0);
    System.out.println(bm.doRefuel());
    bm.ignite();
 }
}

Java 抽象類別

Java 抽象類別的使用:(hint: 把所有類別重複的東西,描象化成一個 super 類別!)
public abstract class Vehicle{
  
   private int wheels;
   private String engineType;
   private double weight;

   Vehicle(int wheels, String engineType, double weight){
       setWheels(wheels);
       setEngineType(engineType);
       setWeight(weight);
   }

   public abstract void ignite(); //這是抽象方法

   public int getWheels(){
     return this.wheels;
   }

   public String getEngineType(){
     return this.engineType;
   }

   public double getWeight(){
     return this.weight;
   }

   public void setWheels(int wheels){
     this.wheels = wheels;
   }

   public void setEngineType(String engineType){
     this.engineType = engineType;
   }

   public void setWeight(double weight){
     this.weight = weight;
   }
}

利用繼承,才能使用抽象類別:
public class Sedan extends Vehicle{

    private char audioClass;

    Sedan(int wheels, String engineType, double weight, char audio){
      super(wheels,engineType,weight);
      this.audioClass = audio;
    }

    //實作抽象方法
     public void ignite(){
       System.out.println("Engine start!");
    }
}

實作時,不可以實例化抽象類別:
public class Demo {
 public static void main(String[] args){

    //錯誤的範例:
    //Vehicle vo = new Vehicle(4, "Gas" , 1234.32);

    //正確的範例:
    Sedan bm = new Sedan(4, "Diesel" , 2231.21 , 'A');
    bm.ignite();
 }
}

2015年9月9日 星期三

Java 例外處理

Java 例外處理(基本處理方式):
import java.util.Scanner;

public class ErrorDemo{

 public static void main(String[] args){
 
  int input = 0;
  Scanner scanner = new Scanner(System.in);
  System.out.print("請輸入一個整數:");
  try{
   input = scanner.nextInt();
  } catch (Exception e){
   System.out.println("請輸入整數!");
  }
 }
}

使用 throws & throw :
public class TestArray{

 int [] intArray;
    public TestArray(int size){
  intArray = new int[size];
 }
 
 public void addElement(int index, int value) throws RuntimeException{
  intArray[index] = value;
  throw new ArrayIndexOutOfBoundsException();
 }
}

public class ExceptionDemo{

 public static void main(String[] args){
 
  TestArray myTestArray = new TestArray(5);
  try {
   myTestArray.addElement(5, 23);
  } catch (RuntimeException e){
   System.out.println("超出陣列大小!");
  }
 }
}

Multi-Exception 的用法:
import java.io.*;

public class MultiExceptionDemo{

 public static void main(String[] args){
 
  try{
   createFile();
  } catch (IOException ex1){
   System.out.println(ex1);
  } catch (IllegalArgumentException ex2){
   System.out.println(ex2);
  } catch (Exception ex3){
   System.out.println(ex3);
  }
 }
 
 public static void createFile() throws IOException{
  File test = new File("C://workspace//test.txt");
  File temp1 = test.createTempFile("te123",null,test);
  System.out.println("Temp filename is " + temp1.getPath());
  int[] myInt = new int[5];
  myInt[5] = 25;
 }
}

好用的 Java Project idea


外國老師提供給學生的 java project  idea !!

http://mindprod.com/project/projects.html

2015年9月2日 星期三

Java 繼承方式

利用繼承來減少程式碼:
public class Clothing{

 private int shirtID = 0;
 private String description = "-----";
 private char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
 private double price = 0.0;
 
 //constructors
 public Clothing(int shirtID, String description, char colorCode, double price){
  setShirtID(shirtID);
  setDescription(description);
  setColorCode(colorCode);
  setPrice(price);
 }
 public void setPrice(double price){
  this.price = price;
 }
 public double getPrice(){
  return this.price;
 }
 public void setDescription(String content){
  this.description = content;
 }
 public String getDescription(){
  return this.description;
 }
 public void setShirtID(int shirtID){
  this.shirtID = shirtID;
 }
 public int getShirtID(){
  return this.shirtID;
 }
 public char getColorCode(){
  return colorCode;
 }
 public void setColorCode(char newChar){
  switch(newChar){
   case 'R':
   case 'G':
   case 'B':
   case 'W':
   this.colorCode = newChar;
   break;
   default:
   System.out.println("This ColorCode is wrong!");
  } 
 }
 
 //顯示 Shirt 相關資料
 public void display(){
 
  System.out.println("Cloth ID: " +  shirtID);
  System.out.println("Description: " + description);
  System.out.println("Cloth Color: " + colorCode);
  System.out.println("Cloth's price: " + price);
 }
}

Shirt 繼承 Clothing 的方式:

public class Shirt extends Clothing{

 private char fit = 'U'; //'S','M','L'
 
 //constructors
 public Shirt(int shirtID, String description, char colorCode,
              double price, char fit){
  super(shirtID,description,colorCode,price);
  setFit(fit);
 }
 public char getFit(){
  return fit;
 }
 public void setFit(char newFit){
  switch(newFit){
   case 'S':
   case 'M':
   case 'L':
   this.fit = newFit;
   break;
   default:
   System.out.println("This Fit is wrong!");
  }
 }
 //Overriding Clothing display method
 public void display(){
  System.out.println("Shirt ID: " +  getShirtID());
  System.out.println("Description: " + getDescription());
  System.out.println("Shirt Color: " + getColorCode());
  System.out.println("Shirt's price: " + getPrice());
  System.out.println("Shirt Fit: " + getFit());
 }
}

執行方式:
public class Demo{

 public static void main(String[] args){
 
  Shirt myShirt = new Shirt(
      321,"NET new Shirt Style!",'B',121.22,'L');
  
  myShirt.display();
 }
}

Java 建構式

Java 建構式與預設建構式:
public class Shirt{

....omit................

//constructors
 Shirt(){}
 
 Shirt(char colorCode){
  setColorCode(colorCode);
 }
 
 Shirt(int shirtID, char colorCode){
  this(colorCode);
  setShirtID(shirtID);
 }

....omit.........

}

執行建構式的方式:
public class Demo{

 public static void main(String[] args){
 
  Shirt myShirt = new Shirt('G');
     
  System.out.println("ColorCode: " + myShirt.getColorCode());
 
 }
}

Java 封裝的方法

Encapsulation 的方式:
public class Shirt{

 private int shirtID = 0;
 private String description = "-----";
 
 //public char colorCode = 'U';//Un-encapsulation
 
 private char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
 private double price = 0.0;
 
 public char getColorCode(){
  return colorCode;
 }
 
 public void setColorCode(char newChar){
  switch(newChar){
   case 'R':
   case 'G':
   case 'B':
   case 'W':
     this.colorCode = newChar;
     break;
   default:
   System.out.println("This ColorCode is wrong!");
  }  
 }

 //顯示 Shirt 相關資料
 public void displayInformation(){
 
  System.out.println("Shirt ID: " +  shirtID);
  System.out.println("Description: " + description);
  System.out.println("Shirt Color: " + colorCode);
  System.out.println("Shirt's price: " + price);
 }
}

執行該物件的方法:
public class Demo{

 public static void main(String[] args){
 
  Shirt myShirt = new Shirt();
  
  //myShirt.colorCode = 'B';
  myShirt.setColorCode('B');
    
  System.out.println("ColorCode: " + myShirt.getColorCode());
 
 }
}