天天看點

Java類方法

文章目錄

方法是在類中聲明的,并且它們用于執行某些操作。舉個例子:

建立一個myMethod()在test1 中命名的方法:

public class test1 {
     static void myMethod() {
            System.out.println("Hello World!");
          }
}
      

當它被 調用時,myMethod()列印文本(動作)。

調用 myMethod():

package test15;

public class test1 {
     static void myMethod() {
            System.out.println("Hello World!");
          }
     public static void main(String[] args) {
            myMethod();
          }
}
      

運作:

Java類方法

你應該經常會看到具有static或public 屬性和方法的Java 程式。在上面的例子中,我們建立了一個static 方法,這意味着它可以在不建立類的對象的情況下被通路,不像public,它隻能被對象通路。

示範static和public 方法之間差異的示例:

package test15;

public class test2 {
    
          // Static method
          static void myStaticMethod() {
            System.out.println("川川呀");
          }

          // Public method
          public void myPublicMethod() {
            System.out.println("java真牛");
          }

          // Main method
          public static void main(String[] args) {
            myStaticMethod(); // Call the static method
            // myPublicMethod(); This would compile an error

            test2 myObj = new test2(); // Create an object of Main
            myObj.myPublicMethod(); // Call the public method on the object
          }
        
}
      
Java類方法

舉個例子:建立一個名為 的 Car 對象myCar。調用對象 上的fullThrottle()和speed()方法myCar,并運作程式

package test15;

public class main {


      // Create a fullThrottle() method
      public void fullThrottle() {
        System.out.println("The car is going as fast as it can!");
      }

      // Create a speed() method and add a parameter
      public void speed(int maxSpeed) {
        System.out.println("Max speed is: " + maxSpeed);
      }

      // Inside main, call the methods on the myCar object
      public static void main(String[] args) {
        main myCar = new main();   // Create a myCar object
        myCar.fullThrottle();      // Call the fullThrottle() method
        myCar.speed(200);          // Call the speed() method
      }

}
      
Java類方法

請記住,java 檔案的名稱應與類名稱比對。在本例中,我們在同一目錄中建立了兩個檔案

  • test3.java
  • test4.java

test3.java:

package test15;

public class test3 {
    
          public void fullThrottle() {
            System.out.println("小車飛快!");
          }

          public void speed(int maxSpeed) {
            System.out.println("最大速度: " + maxSpeed);
          }
    
}
      

test4.java:

package test15;

public class test4 {
      public static void main(String[] args) {
          test3  myCar = new  test3 ();     // Create a myCar object
            myCar.fullThrottle();      // Call the fullThrottle() method
            myCar.speed(200);          // Call the speed() method
          }
}
      
Java類方法