เมธอดของคลาส

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Sani Yusuf

Lead Software Engineering Content Developer

ตัวอย่างคุณสมบัติของรถยนต์

  • รถยนต์มีสีได้
  • รถยนต์แต่ละคันมีรุ่น
  • รถยนต์ทำการกระทำได้ เช่น เปิด/ปิด
  • รถยนต์ให้ข้อมูลได้ เช่น รายชื่ออุปกรณ์ที่เชื่อมต่อ Bluetooth

สีของรถยนต์

รุ่นของรถยนต์

เปิดรถยนต์

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

ประเภทของเมธอด

  • Void methods: เมธอดที่ไม่คืนค่าข้อมูล
  • Non-Void methods: เมธอดที่คืนค่าข้อมูล
Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Void methods

  • Void methods ไม่คืนค่าข้อมูลใด ๆ
  • ระบุด้วยคีย์เวิร์ด void

 // Car class
 class Car {

     void honkHorn() {
      // Code for horn to sound
       System.out.println("beep beep");
      }
 }


$$ $$


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

      Car myNewCar = new Car(); 
      myNewCar.honkHorn(); // beep beep
    }
  }


Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การสร้าง non void methods

  • Non void methods ต้องมีประเภทการคืนค่าเสมอ
  • Non void methods ใช้คีย์เวิร์ด return เพื่อคืนค่าข้อมูล

 // Formula class
 class Formula {


// Non void method int getSquare(int number) { // Return an "int" value return number * number; } }

  // Main class
  public class Main {  
    // main method
    public static void main(
      String[] args) {

      Formula myFormula = 
        new Formula(); 
      // Calling "getSquare" method
      System.out.println(
        myFormula.getSquare(5)); // 25
    }
  }

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

มาฝึกกันเถอะ!

Java เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Preparing Video For Download...