Lecture - Object Oriented Java
Lecture - Object Oriented Java
Object Oriented
Programming in Java
2
Object-Oriented Nomenclature
3
Class and Objects
class Circle {
double radius = 1.0;
double findArea(){
return radius * radius * 3.14159;
}
}
Declaring/Creating Objects
in a Single Step
Example:
Circle myCircle = new Circle();
Accessing Objects
• Referencing the object’s data:
objectReference.data
myCircle.radius
Circle() {
radius = 1.0;
}
… Circle object 1
} 22
}
Instance Variables: Results
Output:
23
Example 2: Methods
class Ship2 {
public double x=0.0, y=0.0, speed=1.0, direction=0.0;
public String name = "UnnamedShip";
24
Methods (Continued)
public class Test2 {
public static void main(String[] args) {
Ship2 s1 = new Ship2();
s1.name = "Ship1";
Ship2 s2 = new Ship2();
s2.direction = 135.0; // Northwest
s2.speed = 2.0;
s2.name = "Ship2";
s1.move();
s2.move();
s1.printLocation();
s2.printLocation();
}
}
• Output:
Ship1 is at (1,0).
Ship2 is at (-1.41421,1.41421).
25
Example 3: Constructors
class Ship3 {
public double x, y, speed, direction;
public String name;
26
Constructors (Continued)
public void move() {
double angle = degreesToRadians(direction);
x = x + speed * Math.cos(angle);
y = y + speed * Math.sin(angle);
}
public void printLocation() {
System.out.println(name + " is at ("
+ x + "," + y + ").");
}
}
public class Test3 {
public static void main(String[] args) {
Ship3 s1 = new Ship3(0.0, 0.0, 1.0, 0.0, "Ship1");
Ship3 s2 = new Ship3(0.0, 0.0, 2.0, 135.0, "Ship2");
s1.move();
s2.move();
s1.printLocation();
s2.printLocation();
}
}
• Output:
Ship1 is at (1,0).
Ship2 is at (-1.41421,1.41421).