Oop lab/example codes
รุ่นแก้ไขเมื่อ 02:08, 10 พฤศจิกายน 2560 โดย Jittat (คุย | มีส่วนร่วม) (หน้าที่ถูกสร้างด้วย '== class และ instance variables == <syntaxhighlight lang="java"> public class Dog { private int weight; private double speed; ...')
class และ instance variables
public class Dog {
private int weight;
private double speed;
private String name;
Dog(String n, int w, double speed) {
name = n;
weight = w;
this.speed = speed;
}
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
public String getName() {
return name;
}
public double getSpeed() {
return speed;
}
public double runDuration(double distance) {
return distance / speed;
}
public double weightOnMoon() {
return ((double)(weight)) / 6.0;
}
public static void main(String[] args) {
Dog d = new Dog("Dang",15, 4.5);
d.sayHello();
System.out.println("It takes " + d.getName() +
" " + d.runDuration(100) +
" seconds.");
System.out.println("In the moon, " + d.getName() +
" weights " + d.weightOnMoon());
}
}