最新文章

LightBlog

2019/10/24

Java物件基本範例



public class MyProg2{

public static void main(String args[]){
Printer MyPrinter = new Printer();   //建立MyPrinter 物件
MyPrinter.No=94079999;
MyPrinter.Hello();
}

}


class Printer{

public int No;

public void Hello(){
System.out.println("Hello! This is my second program.");
System.out.println("My no. is :"+No);
}

}
-----------------------執行結果:--------------------------
E:\test>java MyProg2
Hello! This is my second program.
My no. is :94079999
-----------------------執行結果:--------------------------
Printer:類別
MyPrinter :自訂義變數,也就是"物件"
編譯後會產生兩個 class ( MyProg2.class , Printer.class)
Hello():是類別內的方法

物件公式: 類別 空格 物件(自訂變數) = new 類別()
Printer MyPrinter = new Printer();

-----------------------改寫程式:(不用物件方法)---------------
public class MyProg3{
public static void main(String args[]){
int No=94079999;
System.out.println("Hello! This is my second program.");
System.out.println("My no. is :"+No);
}
}

-----------------------執行結果相同:----------------------
E:\test>java MyProg3
Hello! This is my second program.
My no. is :94079999




-----------------------另一個程式:----------------------

public class ObjCreate{

double i;
void getRandom(){
i=Math.random();
System.out.println(" 亂數值="+i);
}

public static void main(String[] arts){
       ObjCreate a = new ObjCreate(); //建構一個ObjCreate 類別的物件: a
a.getRandom();
}

}
-----------------------執行結果----------------------
E:\test>java Objcreate.java

 亂數值=0.32263392252202405

沒有留言:

Adbox