67
Programmer’s Exam บทที2. Declaration and Access Control การประกาศ และการใช Modifiers กฎของการประกาศ การใช Interface

ความรู้ java

Embed Size (px)

Citation preview

Programmer’s Exam

บทที่ 2. Declaration and Access Control– การประกาศ และการใช Modifiers– กฎของการประกาศ– การใช Interface

Java’s Class

Java’s Class

• ในการสอบสิ่งที่ขอสอบจะวัดเราคือ– สามารถสังเกตการประกาศ class ทีไ่มถูกตองได โดยสวนมาก เปนการ

วัดวา Modifiers วา ตัวใดสามารถใชได ตัวใดไมสามารถใชได– วัดความรูเรา เรื่อง abstract class

– ขอสอบจะถามเรืองการเขาถึง class ใด class หนึ่ง

Sun’s naming convention

1. Sun แนะนําวานักพัฒนาควรตั้งชื่อ package โดยวิธีการ กลบัชื่อ domain ของบริษัทตัวเองcom.jimmysoftware.jsgame

2. ตัวอักษรทุกตัวใน package ตองเปนตัวเล็ก

3. ตัวอักษรตัวแรกของ class ตองเปนตัวใหญ

Class Declarations and Modifiers

1. package package name package name will always be lower case

2. import class name

3. class Classname { } the first letter of the class name will be capitalized

■ สามารถมี class ที่เปน public class ไดแค class เดียวในหนึ่งไฟล■ ชื่อของไฟลตองตรงกับชื่อของ class ที่เปน public

Classes and Objects

• อะไรคือ Class ??• อะไรคือ Object ??

– Class is a description of an Object• Class คือสิ่งที่อธิบายลักษณะของ Object

– Object is an instance of a class• Object คือสิ่งที่ถูกสรางจาก class

Class Accessการเขาถึง class หรือการที่ class ใดๆ สามารถเขาถึง class อื่น

ได สามารถดูไดจาก3 ขอตอไปนี้

1. สามารถสราง object จากclass นัน้ๆ ได 2. หรือ สามารถ สืบทอด class นั้นๆ ได3. หรือ สามารถใช method หรือ variables บางตัวได

Class Access and Nonaccess Modifiers

• Access modifiers สําหรับ class ประกอบดวย 1 ตัวคือ– public

• Nonaccess modifiers สําหรับ class ประกอบดวย 3 ตัวคือ– strictfp , final , abstract

ถึงแมจะม ีAccess modifier 1 ตัว แตจะมี Access level 2 ระดับ

Class Access Level

ในบทนี้ เราจะสนใจแค access level หรือระดับการเขาถึงของ class แค 2 ตัวคือ default กับ public

1. default คือการที่ไมไดใส modifier ไวหนา class , มีเพียง class ใน package เดียวกันที่สามารถ เขาถึงได

package cert;class Beverage {}

////////////////////////////////////////////////////////////////////////////////////package exam.stuff;import cert.Beverage; ///error here can not access from different package

class Tea extends Beverage {}

Class Access Level

2. public คือการที่ใส modifier public ไวหนา class , ทุกclass สามารถเขาถึงได

package cert;public class Beverage {}

////////////////////////////////////////////////////////////////////////////////////package exam.stuff;import cert.Beverage; ///no more error

class Tea extends Beverage {}

Nonaccess Class Modifiers1. strictfp เปนการบอกวา class หรือ method ใช

มาตรฐาน IEEE754 ในการคํานวณทศนิยม

2. final เปนการบอกวา class นั้นๆ ไมสามารถสืบทอดได (can not be subclassed)

Ex. java.lang.Mathjava.lang.String

3. abstract หมายถึง class นั้นๆ ไมสามารถทําการ instantiated ได

• คือ class ที่ไมสามารถถูกสรางเปน object ได จึงมีเพียงหนาทีเดียวก็คือเปน class แมเพื่อให class อืน่สืบทอด

• หาก class ใด classหนึ่งมี method ที่เปน abstract , class นั้นตองเปน abstract class แต abstract class อาจไมมี method ที่เปน abstract เลยก็ได

• การสืบทอด class ที่เปน abstract จะตอง override method ทุกตัวที่ประกาศ เปน abstract ใน class abstract นั้นๆ

Abstract Class

Abstract Class

abstract class Car {private double price;private Color carColor;private String model;private String year;public abstract void goFast( );public abstract void goUpHill( );public abstract void impressNeighbors( );

}

AnotherClass.java:7: class Car is an abstractclass. It can't be instantiated.Car x = new Car();1 error

Class’s Member

Class member

• ในการสอบสิ่งที่ขอสอบจะวัดเราคือ– เรื่องการเขาถึง member ของ class

Memberหมายถงึ variable หรือ method- ในการที่จะประกาศ variable ตองประกอบดวย

1. Access modifier2. Data type ชนดิขอมูล3. Name ชื่อ

- ในการที่จะประกาศ method ตองประกอบดวย1. Access modifier2. Return value3. Name4. List of parameter(optional)5. Thrown exception (optional)

6. Definition of Method

Member Access• public หมายถึงทุก class สามารถเขาถึงได

• protected หมายถึงclass ใน package เดียวกัน และ class ที่สืบทอด สามารถเขาถึงได

• default หมายถึง class package เดียวกัน สามารถเขาถึงได

• private หมายถึง class อื่นๆ นอกจากตัวมันเองไมสามารถเขาถึงได

Member’s Access

public (member)

ภายใน Class สามารถเขาถึงได

ภายใน package สามารถเขาถึงได

class ลูกสามารถเขาถึงได

ทุก class สามารถเขาถึงได

protected (member)

ภายใน Class สามารถเขาถึงได

ภายใน package สามารถเขาถึงได

class ลูกสามารถเขาถึงได

Member’s Access

default(member)ภายใน Class สามารถเขาถึงได

ภายใน package สามารถเขาถึงได

private(member)ภายใน Class สามารถเขาถึงได

Member AccessMember Access

Three ways to access member

1. เรียกใชจากภายใน class 2. เรียกใชผาน reference3. เรียกโดยการสืบทอด

Accessing a private member

Accessing a protected and default member

Java’s Variable

Variable DeclarationsVariable Declarations

การประกาศตัวแปร เราสามารถแบงหมวดหมูของ ตัวแปร ได 2 ชนิดคือ

1. Instance variable คือตัวแปรระดับ class

2. Local variable คือตัวแปรระดับ method ซึ่งประกาศไวภายใน method

Instance VariablesInstance Variables

Instance variable คือตัวแปรระดับ class จะไดรับคาเริมตนเมื่อ object ถูกสราง, Instance variables เปนตัวแปรเฉพาะของแต ละ object

Instance variable จะไปอยูที่ heap พรอมๆกับ object และการไปอยูที่ heap จึงทําให Instance variable ไดรับคา default value

■ สามารถใช access level ทั้ง 4■ สามารถใส modifier final■ สามารถใส modifier transient■ ไม สามารถใส modifier abstract■ ไม สามารถใส modifier synchronized■ ไม สามารถใส modifier strictfp■ ไม สามารถใส modifier native

Local (Automatic/Stack/Method) VariablesLocal (Automatic/Stack/Method) Variables

Local variable คือตัวแปรระดับ method ซึ่งประกาศไวภายใน method นั้นหมายความวา ตองใหคาเริมตน และ ประกาศชนิดขอมูลใหกับ Local variable ใน method และเมื่อโปรแกรมสิ้นสุดการทํางานของ method นั้นๆที่ Local variable ถูกประกาศอยู Local variable ก็จะถูกกําจัดออก

Local variable จะอยูที่ stack จึงทําใหไมได รับคา default value และกอนการใชงานทุกครั้งตองไดรับการใหคาแลว เทานั้น

■ สามารถใช ไดกับmodifier final เทานั้น

Local variables จะอยูที่ stack เทานั้น

Comparison of modifiers on variables Comparison of modifiers on variables vsvs methodsmethods

Nonaccess Member ModifiersNonaccess Member Modifiers

• abstract ใชกับ method เปนการบอกวาclass ที่สืบทอดตอง implement method นั้นๆ

• transient ใชกับ instance variable เพื่อไมใหถูก serialized• synchronized ใชกับ method เพื่อเปนการบอก Jvm ใหรูวาสามารถมีไดแค 1

thread ใชmethod นั้น ได• native ใชกับ method เพื่อบอกวามีการเรียกใช lib ของภาษาอื่น• strictfp ใชกับ method เพื่อบอกใหรูวา method นั้นๆ ใชมาตรฐาน เลข

ทศนิยม IEEE754• static ใชกับ method หรือ instance variable• final ใชไดกับทุกตัว

Java’s Method

Abstract MethodAbstract Methodabstract method คือ method ที่บังคับให class ลูก ที่สืบ ทอด class ทีป่ระกาศ abstract

method นั้น ทําการ override , method ที่เปน abstract จะไมมีการประกาศเนื้อหา method ( ไมมีปกกา )

ตัวอยาง เชนpublic abstract void goFast();public abstract void goUpHill();

Abstract MethodAbstract Method

abstract run();abstract startEngine();

abstract class Car

void run(){}void startEngine(){}

void openWindow(){}

class Toyota

Abstract MethodAbstract Method• method ที่ประกาศเปน abstractไมสามารถประกาศรวมกับ final, private,

synchronized, strictfp และ native

abstract synchronized void foo();abstract strictfp void foof();abstract native void poof();MyClass.java:18: illegal combination of modifiers: abstract and synchronized

abstract synchronized void foo();MyClass.java:19: illegal combination of modifiers: abstract and strictfp

abstract strictfp void foof();MyClass.java:20: illegal combination of modifiers: abstract and native

abstract native void poof();

abstraction

Final modifierFinal modifier

คือ variable ที่ เมือกําหนดคาเริมตนใหแลวไมสามารถกําหนดคาให variable ตัวนั้นอีกได

คือ method ที่ไมสามารถให class ลูก ทําการ overridemethod ได

Final variable

class FinalTest{//Example 1final int x = 30 ;public void showFinal() {

x = 40; // compiler error}

}

Final variableclass FinalTest{ //Example 2

final int x; // Will not work unless x is assigned in the constructor

public void showFinal() {

System.out.println("Final x = " + x);

} //////////error

class FinalTest{final int x; // Will work because it's initialized in the constructorpublic FinalTest() {

x = 28; // The compiler is relieved that we took care of itSystem.out.println("Final x = " + x);

}}

}/////////////no more error

Final ReferenceFinal Referenceคือ reference ที่เมื่อ กําหนดคาเริมตนให ชี้ไปยัง object ใด

ไมสามารถกําหนดใหชี้ไปยัง object อื่นได

import java.util.Date;class TestClass {

final Date d = new Date();public void showSample() {

d.setYear(2001); //เปลี่ยนแปลงคาป ไดไมเปนไร}

}

Final ReferenceFinal Reference

import java.util.Date;class FinalTest {

final Date d = new Date(); // ใหคาเรมิตนแก dpublic void showSample() {

d.setYear(2001);d = new Date(); //ไมสามารถใหชี้ไปยงั object ใหมได

}}

ERROR !!!!!

การใช modifier final

Transient VariablesTransient VariablesJvm จะไมทําการ serialize instance variable ที่ประกาศเปน transient

“transient can be applied only to instance variables.”

Static Variables and MethodsStatic Variables and MethodsStatic

• ทําให field หรือ method ไมเกี่ยวกับ class ใดๆ แต มันจะกลายเปน member global ไปเลย และ class อื่นๆ สามารถเรียกใชโดย ไมตองสืบทอด

• field หรือ method ปกติจะไมมีจนกวาจะไดรับการ new class แต field หรือ methodที่เปน static จะถูกเก็บในหนวยความจําเมื่อ มีการโหลด class

• การเรียกใช member ที่เปน static โดยการ className.staticMemberex. System.out.println();

class Frog {static int frogCount = 0; // Declare and initialize static variable

public Frog() {frogCount += 1; // Modify the value in the constructor

}

public static void main (String [] args) {new Frog();new Frog();new Frog();System.out.println("Frog count is now " + frogCount);

}}

What is the result?

Static

class Frog {int frogCount = 0; public Frog() {

frogCount += 1; }

public static void main (String [] args) {new Frog();new Frog();new Frog();System.out.println("Frog count is now " + frogCount);

}}

What is the result?

Static

• Method ที่เปน static หากจะเรียก variable ที่ประกาศไวนอก method นั้นๆ variableที่ตองการจะเรียกตองเปน static เหมือนกนัเทานั้น

• สามารถเรียก variable หรือ method ซึ่งอยูตาง class ที่เปน static ไดดวยไมตองสราง object ของ class นั้นๆ

Accessing Static Methods and Variables

class Frog {static int frogCount = 0; // Declare and initialize static variablepublic Frog() {

frogCount += 1; // Modify the value in the constructor}

}class TestFrog {

public static void main (String [] args) {new Frog();new Frog();new Frog();System.out.print("frogCount:"+Frog.frogCount);

}}

Accessing Static Methods and Variables

แนวขอสอบclass Foo {

int x = 3;float y = 4.3f;public static void main (String [] args) {

for (int z = x; z < ++x; z--, y = y + z) {// complicated looping and branching code

}}}

Static Variables and MethodsStatic Variables and MethodsMethod ที่เปน static ไมสามารถถูก override ไดสิ่งที่สามารถประกาศเปน static ได■Methods■ Variables■ Top-level nested classes

สิ่งที่ไมสามารถประกาศเปน staticได■ Constructors ■ Classes■ Interfaces■ Inner classes■ Inner class methods and instance variables■ Local variables

Source Files, Package Declarations, and Import Statements

Source Files, Package Declarations, and Import Statements

■ มี public class ไดแค 1 classตอหนึ่งไฟล■ ชื่อของไฟลตองตรงกับชื่อของ public class■ ถาหากclass มี package ชื่อ package ตองอยู บรรทัดแรก■ Import กับ package statements จะมีผลตอทุก class

ในไฟล■ ถามี import statements มันตองอยูระหวาง package

statement กับชื่อ class

การใช Import StatementsImport Statements

มีสอง แบบ คือ1. Wildcard import คือการimport ทุก class ซึ่งอยูใน

package นั้น import java.util.*;

2. Explicit class import คือการเจาะจงเฉพาะวาจะ import แค class ใด class หนึ่ง

import java.util.Arraylist;

1. Use an import statement,import com.wickedlysmart.Foo;class Bar {

void doStuff() {Foo f = new Foo(); // Now the compiler knows which one to use

}}

2. Use the fully qualified name throughout your code:class Bar {

void doStuff() {com.wickedlysmart.Foo f = new com.wickedlysmart.Foo(); // No doubts

}}

การใช Import StatementsImport Statements

แนวขอสอบimport java.awt.*;import java.util.*;class TestImport {

void doStuff() {List fromAWT = new List(); List fromUtil = new List();

}}

Formatting the Main() MethodFormatting the Main() Method■ ตองเปน static.■ ตอง return คา void■ ตองมี String array argument.■ สามารถตั้งชื่อ argument เปนอะไรก็ได■ ตองประกาศเปน public

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

}

Interface

InterfaceInterfaceInterface จะมีแต abstract method หรอืเปนเสมือน pure abstract class• สิ่งที่ interface เหมือน class

– 1. can have any amount of method– 2. interface *.java– 3. interface bytecode is *.class– 4. interface are in a package

• สิ่งที่ interface ไมเหมือน class– 1. can't new– 2. no constructor– 3. all methods are public abstract– 4. all fields are final public static– 5.can't be extend but must be implement– 6. can implement many interfaces

Variable และ method ของ interfacemethod ของ interface ตองเปน■ public■ abstract

Variable (constant) ของ interface ตองเปน■ public■ static■ final

หากเราไมใส modifier jvm จะเติมใหเราเอง

Declaring Interface ConstantsDeclaring Interface Constantspublic interface Bounceable {

int LOW_GRAVITY = 1;int MEDIUM_GRAVITY = 2;int HIGH_GRAVITY = 3;int LOW_BOUNCE = 4;int MEDIUM_BOUNCE = 8;int HIGH_BOUNCE = 12;void bounce();void setBounceFactor(int bounceFactor);void setGravity(int gravity);

}

public final static int LOW_BOUNCE = 4;public final static int HIGH_GRAVITY = 3;

Declaring Interface ConstantsDeclaring Interface Constants

Interface ImplementationInterface Implementationสิ่งที่สามารถประกาศใน interface ไดvoid bounce();public void bounce();abstract void bounce();public abstract void bounce();abstract public void bounce();สิ่งที่ประกาศใน interface ไมไดfinal void bounce(); // final and abstract can never be usedstatic void bounce(); // interfaces define instance methodsprivate void bounce(); // interface methods are always publicprotected void bounce(); // (same as above)synchronized void bounce(); // can’t mix abstract and synchronizednative void bounce(); // can’t mix abstract and nativestrictfp void bounce(); // can’t mix abstract and strictfp

interface

การสืบทอด interfaceการสืบทอด interface หรือการ implement interface มี

2 ลักษณะคือ1. Class ปกต ิสืบทอด interface

• จะใช keyword implements

2. Interface สืบทอด interface ดวยกัน• จะใช keyword extends

1. Class ปกติ สืบทอด interface

public class Ball implements Bounceable { // Keyword 'implements'public void bounce() { }public void setBounceFactor(int bf) { }public void setGravity(int gravity){}}

abstract class Ball implements Bounceable { }public class Ball implements Bounceable, Serializable,Runnable { … }

Class หนึ่งสามารถ สืบทอด ไดหลาย interface โดย keyword implement

2.Interface สืบทอด interface

public interface Bounceable extends Moveable { }public interface Bounceable extends Moveable , Serializable { }

public class Programmer extends Employee, Geek { } // Illegal!

Interface สามารถ สื่อทอด interface ดวยกันไดไมจํากัด โดยคําสั้ง extendsแตไมสามารถ implement อะไรได

Variable และ method ของ interfacemethod ของ interface ตองเปน■ public■ abstract

Variable (constant) ของ interface ตองเปน■ public■ static■ final

หากเราไมใส modifier jvm จะเติมใหเราเอง

Lab 1 การสืบทอด1. ทําการสราง class ชื่อวา myMath.java2. สราง method ชื่อวา plus ซึ่งมี parameter 2 ตัวคือ x กับ y method นี้มีการ return คา int

โดยจะ return ผลบวกของ int x กับ int y3. ทําการ compile myMath แลวดูวามี error อะไรบาง หาก ไมมีใหทําขอตอไป4. สราง class อีก classหนึ่งชื่อวา myMathEx.java ซึ่ง class นี้จะสืบทอด class myMath โดยใช

คําสั่ง extends5. ใน method main ใหสราง object จาก class myMathEx ชื่อวา my แลวเรียก ใช my.plus

argument ที่ตองสงไปให method plus คือ args[0] และ args[1] เพื่อสง parameter x กับ y ไปให method plus ของ myMath ที่สืบทอดมา จากนั้น ทําการแปลง String เปน int โดย

int x =Integer.parseInt(args[0]) ;สิ่งที่ตองการคือ

java myMathEx 10 20แลวโปรแกรม แสดงผล 30