คอนสตรัคเตอร์และการสืบทอด

15:55 ---

คลาสลูกที่สืบทอดมาจากคลาสแม่สามารถมีคอนสตรัคเตอร์ได้เช่นกัน  จากตัวอย่างคลาสสามเหลี่ยมที่สร้างขึ้น มีคอนสตรัคเตอร์ไว้กำหนดความยาวของด้านต่างๆได้โดยสร้างเมธอดมีชื่อเดียวกับคลาสลูก

class Triangle extends TwoDShape{
String style;
Triangle (String s,double w,double h){//คอนสตรัคเตอร์คลาสTriangle
setWidth ( w);//กำหนดความกว้างโดยเรียกเมธอดคลาสแม่
setHeight (h );
style = s;//กำหนดstyleจากพารามิเตอร์ที่รับเข้ามา
}
double area(){ //เมธอดคำนวณพื้นที่ความกว้างwidth
return getwidth*getheight/2; //และตัวแปร heightจากคลาสแม่คำนวณ
//เรียกใช้ตัวแปรwidth,height

}
void showStyle(){// เมธอดสำหรับแสดงstyle
System.out.println("Triangle is "+style);
}
}

คอนสตรัคเตอร์ที่สร้างขึ้นกำหนดความยาวด้านไปเรียกเมธอดคลาสแม่ โดยค่ากำหนดจะเป็นค่าที่รับพารามิเตอร์เข้าไป

ถ้าคอนสตรัคเตอร์กำหนดความกว้างในคลาสแม่ ให้คอนสตรัคเตอร์คลาสลูกไปเรียกใช้คอนสตรัคเตอร์ในคลาสแม่สามารถทำได้ โดย

super ( parameters -​list );

พารามิเตอร์ของsuperคือค่ากำหนดให้คอนสตรัคเตอร์ของคลาสแม่คลาสTwoDShape,Triangleเขียนใหม่โดยสร้างคอนสตรัคเตอร์คลาสแม่ให้คลาสลูกเรียกใช้คอนสตรัคเตอร์คลาสแม่ได้

class TwoDShape{ //คลาส2มิติ
private double  width;//ตัวแปรเก็บความกว้าง
private double height;//ตัวแปรเก็บความสูงของรูปร่าง
TwoDShape(double w,double h ){//สร้างคอนสตรัคเตอร์กำหนดความกว้างและความสูง
width =w;
heigth=h;
}
//สร้างเมธอดข้าถึงwidth,height
double getWidth (){return width;}
double getHeigth (){return heigth;}
void setWidth (double w){width = w;}
void setHeigth (double w){heigth = w;}
void showDim() //เมธอดใช้แสดงความกว้างและสูง
System.out.println("Width and height are"+width+"and"+height);
}
}
class Triangle extends TwoDShape{
private String style;
Triangle (String s,double w,double h){//คอนสตรัคเตอร์คลาสTriangle
Super (w,h );
style = s;//กำหนดstyleจากพารามิเตอร์ที่รับเข้ามา
}
double area(){ //เมธอดคำนวณพื้นที่ความกว้างwidth
return getwidth*getheight/2; //และตัวแปร heightจากคลาสแม่คำนวณ
//เรียกใช้ตัวแปรwidth,height

}
void showStyle(){// เมธอดสำหรับแสดงstyle
System.out.println("Triangle is "+style);
}
}

คลาสแม่และลูกมีคอนสตรัคเตอร์ของตัวเอง.  superจะเรียกคอนสตรัคเตอร์จากคลาสแม่ โดยรับพารามิเตอร์เข้าไปแล้วส่งให้คอนสตรัคเตอร์แม่
Shapes2.javaสร้างobjคลาสTriangle โดยที่คลาสTriangle สร้างคอนสตรัคเตอร์ไว้ โดยสร้างobjชื่อt1,t2พร้อมส่งข้อมูลเริ่มต้นเข้าไป

class Shape2{
public class void main(String args[]){
//สร้างอ็อบเจ็คและส่งค่าเริ่มต้น
Triangle t1 = new Triangle("isosceles",4.0,4.0);//สร้างobj 3เหลื่ยม t1
Triangle t2 = new Triangle(" right",8.0,12.0);//สร้างobj 3เหลื่ยม t2
System.out.println("info for t1");
t1.showStyle();เรียกshowStyleที่อยู่ในคลาส Triangle
t1.showDim();เรียกshowDim()ที่อยู่ในคลาส TwoDShape
System.out.println("Area is"+t1.area());// แสดงพื้นที่ของ3เหลี่ยมt1
System.out.println();
System.out.println("info for t2:");
t2.showStyle();
t2.showDim();
System.out.println("Area is"+t2.area());// แสดงพื้นที่ของ3เหลี่ยมt2
}
}

หลายรูปแบบ(Polymorphism)

01:48 ---
ยอมให้คลาสทั่วไปมีฟังชั่นการทำงานร่วมกันได้ จะทำให้อ็อบเจ็ค  ที่มีในโปรแกรมสามารถทำงานจากคำสั่งเดียวกันในโปรแกรม จากนั้นอ็อบเจ็คก็จะทำตามรูปแบบที่กำหนดไว้ในตัวเอง

การจัดการไฟล์

01:23 ---

ข้อผิดพลาด(exception)

BadArray.javaแสดงข้อมูลเกินข้อมูลที่เก็บจริง
public class BadArry {
public static void main( String[]arge ){
int []number={  1,2,3};//กำหนดค่าในอาร์เรย์3คำ
for (int i=0;<=3; i++)//วนลูป4ครั้ง
System.out.println (number [ i] ); //แสดงค่าnumberที่มีอินเด็กซ์เป็น0,1,2,3
}
}
ค่าอาเรย์numberมีอยู่3เซลล์ คือเซลล์ที่มีอินเด็กซ์เป็น0ถึง2 แต่โปรแกรมจะอ่านเซลล์number[ 3]มาแสดงผลเมื่อรันโปรแกรมจะแจ้งข้อผิดพลาด( Runtime exception)

ดักจับข้อผิดพลาดและจัดการกับข้อผิดพลาด (excepion handling)

จะไม่ให้โปรแกรมหยุดทำงานไปเฉยๆเมื่อมีข้อผิดพลาดเกิดขึ้น คำสั่งtry-catchและคำสั่งthrow
คำสั่งtry-catch
จัดการmethodหรือคำสั่งต่างๆ ที่ผิดพลาด
try
{
ชุดคำสั่งเกิดexception
}
catch( ExceptionType parameterName)
{
ชุดคำสั่งที่จะทำเมื่อดักจับexceptionได้
}
โดยที่exception type คือประเภทที่คลาสต้องดักจับ ส่วนparameterNameคือตัวแปรที่นำมารับข้อผิดพลาดที่เกิดขึ้น
--------------------------------------------------------------------------------------------------------------------
ใช้try-catch ตรวจจับข้อผิดพลาดในmethods.  parselnt. methods ที่เปลี่ยนตัวเลขรูปสตริงให้เป็นจำนวนเต็ม

public  class  ParselntError{
public static void main(String[] args){
String str = "abcde"; //กำหนดตัวแปรเป็นสตริง
int number;               //ประกาศตัวแปร numberเป็นจำนวนเต็ม
try
{
number = integer.parselnt(str);
}
catch (NumberFormatException e)//หากมีความผิดพลาดให้ทำสเตตเมนต์ที่ตามมา
{
System.out.println("Conversion error:"+e.getMeessage());
}
}
}

       strเป็นสตริงที่เป็นตัวแปรอักขระ ทำให้เมธอด parselnt ไม่สามารถเป็นจำนวนเต็มได้ จึงเกิดข้อผิดพลาดขึ้น  และโปรแกรมจะไปทำชุดคำสั่งหลังcatch ซึ่งจะนำobjectที่ดักจับมาแสดงผล
       

คำสั่ง throws


เมธอดดักจับException เขียนthrowsเพื่อประกาศเมธอด เพื่อเป็นการระบุว่าว่าอาจมีความผิดปกติเกิดขึ้น

return_type name(parameter) throws ExceptionType

คำสั่งที่เก็บอยู่ใน java.io.* จะต้องใช้ try-catch,throws ก็ได้

import java.io.*;
public class ReadData{
public static void main(String[]args) throws IOException{
//ใช้throws IOException
byte[]data=new byte[10];
System.out.println("ป้อนตัวอักขระ :");
System.in.read(data);
System.out.println((char)data[i]0; //แสดงข้อมูลในอาร์เรย์ออกมาทีละตัว
}
}

เมื่อรันโปรแกรมเมธอด read จะให้ป้อนข้อมูลเข้าไปแล้วกด<Enter>ข้อมูลนี้จะถูกเก็บในตัวแปรอารเรย์คำสั่งนี้มีตัวจับความผิดพลาดอยู่ด้วย จากนั้นจะพิมพ์ข้อมูลทั้งหมดในอาเรย์ออกมาทีละตัว

-----------------------------------------------------------------------------------------------------------------------
ใช้เมธอด read(int[]) เพื่อรับข้อมูลเก็นในตัวแปรอาร์เรย์ การใช้เมธอด System.in.read นี้จะต้องเรียก java.io.* ขึ้ันมาก่อน และเมธอดนี้จะต้องตรวจจับข้อผิดพลาดด้วย จึงใช้คำสั่ง throws ในการตรวจจับ

import java.io.*;
public class ReadData{
public static void main(String[]args){
byte[]data = new byte[10];
System.out.println("ป้อนตัวอักขระ:");
try                                                        //ตรวจจับข้อผิดพลาดจากบล็อกคำสั่งที่ตามมา
{
System.in.read(data);
System.out.println("พิมพ์:");
for(int i=0;i<data.length;i++)
System.out.println((char)data[i]);
}
catch(Exception e)                             //หากมีข้อผิดพลาดทำบล็อกที่ตามมา
{
System.out.println("ป้อนข้อมูลผิดพลาด:");
}
}
}

--------------------------------------------------------------------------------------------------------------------
หาไฟล์ตัวเลขแล้วบันทึกไฟล์ชื่อ number.txt
import java.io.*;
public class FileSum{
public static void main(String[]args)throw IOException{
double sum;                                                                      //ประกาศตัวแปรสำหรับหาผลรวม
String str;                                                                        //ประกาศตัวแปรที่เก็บข้อมูลที่อ่านขึ้นมา
FileReader freader = new FileReader("number.txt");   //เปิดไฟล์
sum =0.0                                                                      //กำหนดค่าเริ่มต้นของผลรวมเป็น0
str = inputFile.readLine();                                          //อ่านข้อมูลขึ้นมา1บรรทัด
while(str != null)                                                       //ตรวจสอบว่าสิ้นสุดไฟล์หรือยัง
{                                                                               //ถ้ายังอ่านต่อ
sum =sum+Double.parseDouble(str);                    //เปลี่ยนสตริงที่อ่านได้ให้เป็นทศนิยมแล้วหาผลรวม
str= inputFile.readLine();                                     //อ่านข้อมูลบรรทัดต่อไป
}
inputFile.close();                                               //ถ้าจบแล้วเปิดไฟล์
System.out.println("The sum of the number in"+"Numbers.txt is"+sum);
}
}

เมธอดต่างๆมีการตรวจจับ throw IOException สามารถใช้ try-catch ได้ 







SimpleFileReader.javaเป็นโปรแกรมอ่านไฟล์แสดงผลที่ละอักขระใช้การตรวจจับความผิดtry-catch

import java.io.*;
public class SimpleFileReader{
public static void main(String[]args){
int rawData;//ตัวแปรสำหรับเก็บรหัสของตัวอักขระ
char ch;//ตัวแปรเก็บตัวอักขระ
try//ตรวจสอบความผิดพลาด
{
FileReader freader = new FileReader("GoodFile.txt");//เปิดไฟล์
rawData =freader.read() //อ่านตัวอักระขึ้นมาหนึ่งตัว
while(rawData != -1) //ตรวจสอบว่าสิ้นสุดไฟล์หรือยัง
{
ch = (char) rawData;//เปลี่ยนระหัสให้เป็นอักขระ
System.out.print(ch);//แสดงผลทางหน้าจอ
rawData = freader.read(); //อ่านตัวอักขระตัวต่อไป
}
}
catch(IOException e) //ถ้ามีความผิดพลาดเกิดขึ้นให้ทำชุดคำสั่งด้านล่าง
{
System.out.println("Error:"+e.getMeessage());
}
}
}





การเขียนสตริงลงในไฟล์ ใช้การดักจับแบบthrows ไฟล์ชื่อ testWriteData.txt

import java.io.*;
public class writeFile{
public static void main(String[]args)throw IOException{//ดักจับความผิดพลาด
String letter = "This is test data"; //กำหนดข้อมูลสตริง
FileWriter fw = new FileWriter("WriteData.txt");//เปิดไฟล์
fw.write(letter,0,17);//เขียนตัวอักขระ17ตัวตั้งแต่ตัวที่0
fw.write("Test Write data to File A-Z"+"\n");//เขียนข้อความสตริงค์ลงในไฟล์
for(int i=65;i,91;i++)//วนลูปเขียนตัวอักษร
fw.write((char)i);//เปลี่ยนตัวเลขให้เป็นอักขระ
fw.close();//ปิดไฟล์
System.exit(0);
}
}




การจัดการerror with exception

23:40 ---
การจัดการ error คือ แยกส่วนที่คอยจัดการ error ออกจากcodeปกติ
  • exception class ให้sup class ที่ระบุชนิดของerrorต่างๆของโปรแกรม
  • error class เกี่ยวข้องกับ java Virtual Machine failure, dynamic linking failure ซึ่ง errorเหล่านี้ไม่จำเป้นต้องcatch
  • Runtime Excepion เกี่ยวข้องกับ error ใน java Virtual Machine ระหว่าง runtime ซึ่ง error เหล่านี้ไม่ต้องcatch แม้ว่าสามารถทำได้
สาเหตุการเกิดexception มี3ชนิด
Abnormal execution condition เช่น error ต่างๆ ที่เกิดขึ้นในโปรแกรมจาการทำผิดกฎ
throw statement
Asynchronous exception  เช่น เมื่อใช้ stop method,มี internel error เกิดขึ้นในjava Virtual Machine 

โครงสร้างการจัดการ exception

try
{
java statements เป็นสาเหตุให้เกิด exception โดยจะโยน exception
}
catch(ชนิดexceptionที่เกิดe)
{
java statement ที่จัดการ exception
}
-------------------------------------------------------------------------------
try
{
java statements เป็นสาเหตุให้เกิด exception โดยจะโยน exception
}
catch(ชนิดexceptionที่เกิดe)
{
java statement ที่จัดการ exception
}
...
catch(ชนิดของexception ที่เกิด N e)
{
java statement ที่จัดการexception
}
------------------------------------------------------------------------------

try
{
java statements เป็นสาเหตุให้เกิด exception โดยจะโยน exception
}
catch(ชนิดexceptionที่เกิดe)
{
java statement ที่จัดการ exception
}
...
finally()
{
java statement ที่จัดการเสมอไม่ว่าจะมีexceptionเกิดขึ้นหรือไม่
}

try statement จะต้องมี catch block หรือ finally block (สำหรับปิดไฟล์หรือปลดปล่อยทรัพยากรในระบบ) catch block จะดักจับexception ที่ถูกโยนมาจากtry blockด้วย exception handler มีสองรูปแบบ คือ NoSuchElementExceptionซึ่งเป็น sup classของ ArrayException ซึ่งเป็น sup classของexception class

  • General exception handler โดยsupper class ของerror
catch (Exception e)
{
...
}
catch (ArrayException e)
{
...
}

  • Specific exception handler ใช้คลาสตามชนิดของ errorที่เกิดขึ้น

catch (NoSuchElementException e)
{
...
}
ไม่นิยมGeneral exception handler เพราะจับ errorที่ไม่เกี่ยวข้องมาด้วย


แสดงexception ที่เกิดเรามี4สามาชิกอาเรย์ แต่อ้างอิง 5 สามาชิก (0 =< i =< 5       =0,1,2,3,4)

char[]x={'a','b','c','d'};

try
{
for(int i=0;i<5;i++)
System.out.println(""+ x[i]);
}
catch(Exception e)
{
System.out.println("Error"+e);
}

keyword this และ super

22:41 ---

super 

ภายใน method body เพื่ออ้างถึง hidden variable หรือ overridden method ของsuper classเช่น

class MySuperclass
{
boolean myVariable;
void myMethod()
{
myVariable = true;
}
}
class MySubclass extends MySuperclass
{
boolean myVariable;
void myMethod()
{
myVariable = false;
super.myMethod();
System.out println(myVariable);
System.out println(super.myVariable);
}
}

ผลลัพธ์ false
              true


keyword this

class Circle
{
int pointX,pointY,radius;
public Circle(int pointX,int pointY,int radius)
{
this.pointX=pointX;
this.pointY=pointY;
this.radius=radius;
}
}

overriding

22:28 ---
overriding  คือsup class ที่ไม่ใช้ method เดิมที่มาจาก super class แต่จะเปลี่ยนmethod  ต้องคงชื่อชนิดreturn ,จำนวนชนิดของอาร์กิวเมนต์เดิมไว้
methodนี้เมื่อถูก override โดยsubclass เป็นpublicได้เป็น private ไม่ได้
เช่น นาย ก. มีความเป็นชายมาจากพ่อแม่ แต่ไม่พอใจในสิ่งนั้น ไปผ่าตัดแปลงเพศ ทำสิ่งนั้นในอีกหน้าหนึ่งแทน

Abstract class

22:19 ---
Abstract class คือ super class ระบุคุณสมบัติทั่วไป
Abstract classไม่สามารถใช้ตามลำพังได้ มันจะถูก inheritโดย sub class
Abstract class ไม่สามรถสร้างobjectได้

interface

22:10 ---
เครื่องมือติดต่อกับสิ่งที่ไม่มีความสัมพันธ์ต่อกัน
multiple inheritance คือ class สามารถ inherit จากinterfaceได้เพียง constant
แต่interface จะ inherit ทั้ง method และ constant จาก superinterfaces และแต่ละคลาสอาจมี interface เดียวกันได้

รูปแบบ interface


public interface ชื่อ interface extends superinterfaces
{
Interface body
}

public= แสดงว่าอินเตอร์เฟสสามารถใช้คลาสหรือแพ็กเกตใดๆ ก้ได้ ถ้าไม่ระบุ publicไว้  อินเตอร์เฟสใช้ได้เฉพาะคลาสที่อยู่ในอินเตอร์เฟซ

extend= สามารถ extendได้หลายinterface มี,คั่น

interface โดยใช้คลาส

public class ชื่อclass implements ชื่อInterface
{
......
}

ถ้าเราใช้ abstrace class แทน interface จะไม่สามารถ inherit classอื่นได้อีก เพราะมีข้อจำกัดว่า inheritได้class เดียว จริงๆแล้วเรามีclassที่ต้องinheritจาก sub class อยู่แล้ว

public interface MyInterface
{
Public void methodA();
Public void methodB();
}
pubilc class Myclass implement MyInterface
{
Public void methodA();
{
.......
}
Public void methodB();
{
.......
}
}

inheritance

20:19 ---

inheritance

 การลืบทอดลำดับชั้น สามารถนำคลาสที่มีอยู่แล้วหรือนำโปรแกรมที่มีอยู่แล้วมาเขียนใหม่ได้อีก สามารถสร้าคลาสใหม่สืบทอดคลาสที่มีอยู่แล้วได้เป็นการถ่ายทอดคุณสมบัติคลาสหนึ่งไปยังคลาสหนึ่ง  ทำให้คลาสใหม่นำคุณลักษณะคลาสเดิมมาใช้ได้ คลาสที่เป็นต้นแบบเรียกว่าsuperclass หรือbase class คลาสที่สืบทอดคือ subclassหรือchild class
      การสืบทอดทำให้เราสามารถสร้างคลาสที่ใช้คุณลักษณะต่างๆ เหมือนคลาสเดิม แต่เพิ่มคุณลักษณะเพิ่มเติมลงไป
sub class จะ inherit จาก super class ที่เป็นpublic หรือprotected แต่จะไม่ inheritจากsuper class เป็น private
sub class ที่มีชื่อตัวแปรหรือ method เหมือนอยู่ใน super class ของมัน sub class นั้นจะไม่ inherit ต่อตัวแปร หรือ method ของsuper classของมัน sub classนั้นจะไม่ inherit ต่อตัวแปรหรือ method ของsupper classนั้น methodก็เกิดการ Override ส่วนตัวแปรก็จะซ่อน
เช่นจากคลาสStudent ต้องการสร้างคลาสใหม่ให้เก็บคะแนนฟิสิกส์เพิ่มเติม   ซึ่งจะทำให้อ็อบเจ็กต์ของคลาสใหม่ยังมี id,name,gpa เหมือนเดิม มีคะแนนฟิสิกส์เพิ่มขึ้นมา

รูปแบบการ inheritance

public class subclass extends superclass
{
......
}
เช่น
public class Honda extends car
{
.....
}


การสืบทอดจากคลาสแม่สู่ลูกโดยที่คลาสลูกที่สร้างขึ้นมีลักษณธคล้ายคลาสคลาสแม่  จะมีคุณลักษณะพิเศษเฉพาะกว่าเช่น
มีคลาสรูปร่าง2มิติเป็นคลาสแม่
คลาสลูกเป็นคลาส 3เหลี่ยม 4เหลี่ยม วงกลมสืบทอดมาจากคลาส 2 มิติ การสร้างคลาสใช้คำว่า extends เพื่อบอกว่าสืบทอดมาจากคลาสใด


class TwoDShape{ //คลาส2มิติ
double  width;//ตัวแปรเก็บความกว้าง
double height;//ตัวแปรเก็บความสูงของรูปร่าง
void showDim(){ //เมธอดใช้แสดงความกว้างและสูง
System.out.println("Width and height are"+width+"and"+height);
}
}


Triangle สืบทอดมาจาก TwoDShape 

object นั้นสามารถใช้เมธอดและคุณลักษณะของTwoDShapeได้


class Triangle extends TwoDShape{
String style;
double area(){ //เมธอดคำนวณพื้นที่ความกว้างwidth
return width*height/2; //และตัวแปร heightจากคลาสแม่คำนวณ
}
void showStyle(){// เมธอดสำหรับแสดงstyle
System.out.println("Triangle is "+style);
}
}


Shapes.java สร้างobjectของTriangle คลาสของ3เหลี่ยมมา2ตัว แสดงการเรียกใช้เมธอดและคุณลักษณะภายในคลาส

class Shape{
public class void main(String args[]){
Triangle t1 = new Triangle();//สร้างobj 3เหลื่ยม t1
Triangle t2 = new Triangle();//สร้างobj 3เหลื่ยม t2
t1.width=4.0;//กำหนดความกว้างให้3เหลื่ยม t1
t1.height=4.0;//กำหนดความสูงให้3เหลื่ยม t1
t1.style  ="isosceles";//กำหนดstyle ให้3เหลื่ยม t1
t2.width=8.0;//กำหนดความกว้างให้3เหลื่ยม t2
t2.height=12.0;//กำหนดความสูงให้3เหลื่ยม t2
t2.style  ="right";//กำหนดstyle ให้3เหลื่ยม t2

System.out.println("info for t1");
t1.showStyle();เรียกshowStyleที่อยู่ในคลาส Triangle
t1.showDim();เรียกshowDim()ที่อยู่ในคลาส TwoDShape
System.out.println("Area is"+t1.area());// แสดงพื้นที่ของ3เหลี่ยมt1
System.out.println();
System.out.println("info for t2:");
t2.showStyle();
t2.showDim();
System.out.println("Area is"+t2.area());// แสดงพื้นที่ของ3เหลี่ยมt2
}
}

รูปแบบการ inheritance จากคลาสแม่

public class subclass extends superclass
{
......//โครงสร้างในคลาส
}
เช่น
public class Honda extends car
{
.....
}

คลาสลูกสามารถสร้างมากกว่าหนึ่งคลาสก็ได้ 

class Rectangle extends TwoDShape{
boolean isSquare(){//เมธอดทดสอบว่าเป็นสี่เหลี่ยมจริงหรือไม่
if (width==height )return true;//ถ้าความกว้างเท่ากับความสูงให้คืยค่สจริง
return false;//ถ้าความกว้างไม่เท่ากับความสูงให้คืนค่าเท็จ
}
double area (){ //เมธอดคำนวณพื้นที่
return width*height;
}
}

ถ้าคลาสTwoDShapeเป็นprivateคลาสลูกก็ไม่สามารถใช้ตัวแปรหรือสืบทอดได้

class TwoDShape{ //คลาส2มิติ
private double  width;//ตัวแปรเก็บความกว้าง
private double height;//ตัวแปรเก็บความสูงของรูปร่าง
void showDim(){ //เมธอดใช้แสดงความกว้างและสูง
System.out.println("Width and height are"+width+"and"+height);
}
}
//สร้างคลาสลูก
class Triangle extends TwoDShape{
String style;
double area(){ //เมธอดคำนวณพื้นที่ความกว้างwidth
return width*height/2; //และตัวแปร heightจากคลาสแม่คำนวณ
//จะเกิดการผิดพลาดไม่สามารถใช้ตัวแปรwidth,heightได้

}
void showStyle(){// เมธอดสำหรับแสดงstyle
System.out.println("Triangle is "+style);
}
}


ถ้าจะเข้าถึงwidth,height ต้องสร้างmethods ขึ้นมา
คลาสTwoDShape,Triangle เขียนใหม่

class TwoDShape{ //คลาส2มิติ
private double  width;//ตัวแปรเก็บความกว้าง
private double height;//ตัวแปรเก็บความสูงของรูปร่าง
//สร้างเมธอดข้าถึงwidth,height 
double getWidth (){return width;}
double getHeigth (){return heigth;}
void setWidth (double w){width = w;}
void setHeigth (double w){heigth = w;}
void showDim() //เมธอดใช้แสดงความกว้างและสูง
System.out.println("Width and height are"+width+"and"+height);
}
}

และสร้างTriangle โดยแก้ไขเมธอดที่คำนวณพื้นที่ใหม่
class Triangle extends TwoDShape{
String style;
double area(){ //เมธอดคำนวณพื้นที่ความกว้างwidth
return getwidth*getheight/2; //และตัวแปร heightจากคลาสแม่คำนวณ
//เรียกใช้ตัวแปรwidth,height 

}
void showStyle(){// เมธอดสำหรับแสดงstyle
System.out.println("Triangle is "+style);
}
}


การห้ามสืบทอด

final class TwoDShape {
//โครงสร้างในคลาส
}
หากมีการสืบทอดคลาสนี้ถ้าคอมไฟล์จะคอมไพล์ไม่ผ่าน

03:59 ---
\n ขึ้นบรรทัดใหม่
\t  แท็บแนวนอน
\bถอยหลัง1ช่องตัวอักษร
\r เลือนเคอร์เซอร์ไปซ้ายสุด
\\แสดง\
\' แสดง'
\"แสดง"

public class Tabs{
public static void main (String[] args) {
System.out.print("These are our top sellers:\n");
System.out.print("\tComputer grames\n\tCoffee\n");
System.out.println("\tAspirin");
}
}

ผล
These are our top sellers:
        Computer grames
        Coffee
        Aspirin
Press any key to continue . . .
=======================================================================
boolean  เก็บค่าtrue ,false
char        เก็บอักษรแบบUnicode
byte        -128 ถึง+127
short       -32,768ถึง +32,767
int           -2147483648ถึง +2147483647
long        -263ถึง+263 -1
float        -3.4E+38ถึง 3.4E+38
double    -1.7E+308ถึง1.7+308



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

double m= 3.12;
float x=12.f;

System.out.println(m);
System.out.println(x);
}
}
ผล
3.12
12.0
Press any key to continue . . .
======================================================================
public class increment{
public static void main (String[] args) {
int x,y;
x=10;
y=x++;
System.out.println("x="+x+" y= "+y);
y = ++x;
System.out.println("x="+x+" y= "+y);
}
}

ผล

x=11 y= 10
x=12 y= 12
Press any key to continue . . .

Objects and Primitive Data

03:55 ---

Variables


public class PianoKeys {
public static void main (String[] args) {
int keys = 88;
System.out.println ("A piano has " + keys + " keys.");
}
}
--------------------------------------------------------------------------------------------------------------------------
Compile:
A piano has 88 keys.
--------------------------------------------------------------------------------------------------------------------------
public class PianoKeysErr {
public static void main (String[] args) {
int keys; // declaration without initialization
System.out.println ("A piano has " + keys + " keys.");
}
}
 ก็คือไม่ประกาศint keysว่า=เท่าไหร่ runก็runไม่ได้
--------------------------------------------------------------------------------------------------------------------------
Compile:
C:\myDir\PianoKeysErr.java:6: variable keys might not have
been initialized
System.out.println ("A piano has " + keys + " keys.");
^
1 error
Tool completed with exit code 1
--------------------------------------------------------------------------------------------------------------------------

Assignment

กำหนดค่าตัวแปล ใช้เครื่องหมาย=

total = 5 * 8 - 3; // total is set to 37

ค่าก่อนหน้านี้จะถูกเขียนทับ

total = 10; // total is set to 10
total = 22; // now it is set to 22

สามารถกำหนดเพียงค่าให้กับตัวแปรที่เป็น สอดคล้องกับการประกาศชนิดของตัวแปร
int x = 10; // ok
int y = 10.5; // 10.5 is not an integer

Constants ค่าคงที่

ใช้finalในการประกาศค่าอย่างต่อเนื่อง
final int MIN_HEIGHT = 69;
ชื่อconvention:จะเป็นพิมพ์ใหญ่ทั้งหมด

Primitive Data

ชนิดข้อมูลในjava
แบบจำนวนเต็ม integers:
• byte, short, int, long
ทศนิยม
• float, double
ตัวอักษร
• char
เปรียบเทียบ
• boolean

Numeric Primitive Data

การเก็บข้อมูลตัวเลข
byte, short, int, long, float, double

int เก็บได้มากสุด 2,147,483,647.
floatเก็บได้เพียง7เลข 100,000.875ถ้ามากกว่านั้นใช้ double.

Characters

char เป็น String ได้ถ้ามี
'a'     'X'     '7'     '$'      ','    '\n‘

ความแตกต่างระหว่าง
int x = 1; // x is a number
char y = ‘1’; // y is a character

Boolean

จริงเท็จ
boolean done = false; // ok
boolean x = 1; // won’t compile

Arithmetic Expressions นิพจน์เลขคณิต

+ - * / %
จำนวนกับจำนวนเต็ม=จำนวนเต็ม
ทศนิยมกับทศนิยม=ทศนิยม
จำนวนเต็มกับทศนิยม=ทศนิยม
เช่น

3 * 5 = 15
3 * 5.0 = 15.0

Division and Remainder (Div and Mod)
If both operands to the division operator (/) are integers,
the result is an integer (the fractional part is discarded)
The remainder operator (%) returns the remainder after
dividing the second operand into the first
14 / 3 = 4
8 / 12 =0

14 % 3 =2
8 % 12 =8

Operator Precedence

x = 15 * 4 + 88 % 2 - 11;
result = total + count / max - offset;

• *, /, %
• +, -

What is the order of evaluation in the following expressions?
a + b + c + d + e
1 2 3 4
a + b * c - d / e
3 1 4 2
a / (b + c) - d % e
2 1 4 3
a / (b * (c + (d - e)))
4 3 2 1

Casting

int x = 10, y = 4;
float result;
result = (float) x / y; // result is 2.5
result = (float) (x / y); // result is 2.0

Creating Objects

สร้างวัตถุใหม่อ้างอิงวัตถุเก่า
public class Dog {
}
public void bark () {
...
}
...
public void wag () {
...
}

--------------------------------------------------------------------------------------------------------------------------
Dog myDog = new Dog ();

อ้างอิงและวัตถุยังสามารถสร้างแยกต่างหาก:
Dog myDog;
myDog = new Dog ();

Using Objects

public class Dog {
}
public void bark () {
...
}
...
public void wag () {
...
}

The null Reference

อ้างอิงวัตถุ ว่าง
Dog myDog = new Dog ();
myDog = null;
เมื่อตรวจสอบวัตถุไม่มี
if (myDog == null)
System.out.println ("Invalid");

Garbage Collection