Object Oriented Programming
OOP = programming paradigm. some defns:
- class = blueprint in code (e.g. a bicycle class might have a "speed" variable and a speedUp() method)
- object = instance of a class (e.g. Ronnie's bike)
- abstraction = means hiding what isnt important when working with classes / OOP
- encapsulation = techniques to bundle and hide methods and properties within classes (e.g. using public and private keywords). this is one way to enable abstraction
- inheritance = when new objects to take on the properties of existing objects (e.g. a circle object inherits the properties of a shape object)
- polymorphism = ability for an object to take on many forms (e.g. a method draw() could be used with triangles, stars and boxes)
Player class
a player has a username. if a username isnt supplied when creating an instance of this class, the username is set to "unknown" by the constructor when the object is first created://save as Player.java
public class Player {
//----variables:
public String username;
//----constructors (so no return type):
public Player(){ username = "unknown"; }
public Player(String nameSupplied) { username = nameSupplied; }
//----methods:
public void greet() {
System.out.println("hello " + username);
}
}
our program executes from the main procedure:
//save as mainGame.java
public class mainGame {
public static void main(String[] args) {
Player robert = new Player("3l1t3_5n1p3r");
robert.greet();
Player sally = new Player();
sally.greet();
sally.username = "xX_memelord_Xx";
sally.greet();
}
}