9. Code structure in Java
source file
class file
method 1
statement
method 2
statement
10. Code structure in Java
public class Dog {
!
!
!
!
}
class
public class Dog {
void bark () {
!
!
}
}
method
public class Dog {
void bark () {
statement1;!
! ! statement2;
}
}
statements
12. Writing a class with a main
public class MyFirstApp {
!
public static void main (String[] args) {
System.out.println("I Rule!");
System.out.println("The World!");
}
}
13. Statements
int x = 3;
String name = "Dirk";
x = x * 17;
System.out.print("x is " + x);
double d = Math.random();
// this is a comment
14. Condition
if (x == 10) {
System.out.println("x must be 10");
} else {
System.out.println("x isn't 10");
}
!
if ((x < 3) && (name.equals("Dirk"))) {
System.out.println("Gently");
}
!
if ((x < 3) || (name.equals("Dirk"))) {
System.out.println("Gently");
}
15. Looping
while (x > 12) {
x = x - 1;
System.out.println("x is " + x);
}
!
for (x = 0; x < 10; x = x + 1) {
System.out.println("x is " + x);
}
20. thinking about objects
When you design a class, think about the objects that
will be created from that class type. Think about
• things the object knows
• things the object does
22. What’s the difference between a class
and an object?
• A class is not an object (but it’s used to construct
them)
• A class is a blueprint for an object
24. Class GoodDog
class GoodDog {
private int size;
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;
}
void bark() {
if (size > 60) {
System.out.println("Woof! Woof!");
}
else if (size > 14) {
System.out.println("Ruf! Ruf!");
}
else {
System.out.println("Yip! Yip!");
}
}
}
25. GoodDog Test Drive
public class GoodDogTestDrive {
public static void main (String[] args) {
GoodDog one = new GoodDog();
one.setSize(70);
GoodDog two = new GoodDog();
two.setSize(8);
System.out.println("Dog one: " + one.getSize());
System.out.println("Dog two: " + two.getSize());
one.bark();
two.bark();
}
}
28. Static variables
class Player {
static int playerCount = 0;
private String name;
!
public Player(String n) {
name = n;
playerCount++;
}
}
!
public class PlayerTestDrive {
public static void main(String[] args) {
System.out.println(Player.playerCount);
Player one = new Player("Tiger Woods");
System.out.println(Player.playerCount);
}
!
}