Object Oriented Programming
Defining Classes
Using Classes
Summary
Hamlet: "ToBe || !ToBe..."
Programmer: "True !"
The objects are Data Structures which contains data and can do actions
Represent the real world as objects and relationships between them
Ordinary Car
Do you have more?
Wacky Car
Objects group together:
Car
Car
Objects have actions
Car
Actions represented as methods
public void moveLeft() {
...
}
public void moveRight() {
...
}In the game there are 4 cars with color, top speed, driver and position
So in our program we have:
String car1Color = "red";
int car1TopSpeed = 160;
int car1Position = 1;
String car1Driver = "Ivancho";
String car2Color = "blue";
int car2TopSpeed = 240;
int car2Position = 2;
String car1Driver = "Mariiki";
...
car3
...
car4How to avoid repetition and so much variables?
Create a template for my cars!
A class is the blueprint from which individual objects are created
Define a class Car:
public class Car {
FIELDS
METHODS
}class Car {
public String color;
public int topSpeed;
public String driver;
public int position;
public void moveLeft() {
...
}
public void moveRight() {
...
}
}Car car1 = new Car();
car1.color = "red";
car1.driver = "Ivancho"
Car car2 = new Car();
car2.color = "blue";
car2.driver = "Mariika";
You actualy create new type!
Not going in Galaxy!
public String color;Everybody can change my color
car1.color = "red";private String color;I am the master of my color.
Nobody knows that I have color.
How to be the master of my fields but tell the others that I have color and they can do something about it?
class Car {
private String color;
public void setColor(String c) {
color = c;
}
public String getColor() {
return color;
}
}Do something when I create you
public class CLASSNAME {
CLASSNAME() {
}
CLASSNAME([ARGUMENTS]) {
}
}
CLASSNAME obj1 = new CLASSNAME();
CLASSNAME obj2 = new CLASSNAME([ARGUMENTS]);public class Car {
public String color;
Car() {
}
Car(String someColor) {
color = someColor;
}
}
Car car1 = new Car();
car1.color = "red";
Car car2 = new Car("red");If you don't define constructor, there is an empty one automatically created