Basic object-oriented programming

From Knowledge Kitchen
Jump to navigation Jump to search


This document shows some of the core concepts of object-oriented programming in the Java programming language.

Classes

Classes are custom data types

  • a class is like a plan or template for how data of a custom type should be represented
  • it's easy to think of a class as a mold from which objects are made
  • Plato wrote that all physical objects were mere reflections of ideal forms

Defining of a class

The following examples show how to define a class in various programming languages.

Python example

class Dog:
    age = 0

Java example

class Dog {
    public int age = 0;
}

PHP example

class Dog {
    public $age = 0;
}

Javascript example

function Dog() {
    this.age = 0;
}

Objects

An object is an instance of a class

  • objects are specific implementations of the plan that the class offers
  • the terms instance and object are used interchangeably

Instantiating an object from a class

Instantiation is the process of creating an object. The following examples show how to instantiate two objects in various programming languages based on the class definitions above.

Python example

dog1 = Dog()
dog2 = Dog()

Java example

Dog dog1 = new Dog();
Dog dog2 = new Dog();

PHP example

$dog1 = new Dog();
$dog2 = new Dog();

Javascript example

var dog1 = new Dog();
var dog2 = new Dog();

Constructors

Constructors are special methods that, if present, are executed automatically when a new object is being created. These are most often used to set up the initial settings of an object.

The following examples expand upon the previous class definitions above to include a constructor.

Python example

Class definition with a constructor:

class Dog:
    age = 0
    name = ""

    def __init__(self, age, name):
        print("A new Dog named " + name + " is born!")
        self.age = age
        self.name = name

Instantiate a Dog object using this constructor:

dog1 = Dog(3, "Betsie")
dog2 = Dog(0, "Tobik")

Java example

Class definition with a constructor:

class Dog {
    public int age = 0;
    public String name = "";

    public Dog(int age, String name) {
        System.out.println("A new Dog named " + name + " is born!");
        this.age = age;
        this.name = name;
    }
}

Instantiate a Dog object using this constructor:

Dog dog1 = new Dog(3, "Betsie")
Dog dog2 = new Dog(0, "Tobik")

PHP example

Class definition with a constructor:

class Dog {
    public $age = 0;
    public $name = "";

    public function __construct($age, $name) {
        print("A new Dog named " . $name . " is born!");
        $this->age = $age;
        $this->name = $name;
    }
}

Instantiate a Dog object using this constructor:

$dog1 = new Dog(3, "Betsie")
$dog2 = new Dog(0, "Tobik")

Javascript example

Note that in Javascript, the rentire class definition is itself a constructor method.

Class definition with a constructor:

function Dog(age, name) {
    this.age = age;

    console.log("A new Dog named " + name + " is born!");
    this.name = name;
}

Instantiate a Dog object using this constructor:

var dog1 = new Dog(3, "Betsie")
var dog2 = new Dog(0, "Tobik")

Encapsulation

Any object or class can have attributes and methods that 'belong' to it.

  • Attributes or methods that belong to an object are called instance attributes and instance methods
  • Attributes or methods that belong to a class (but are not 'owned' by any specific instance of that class), are called static attributes and static methods

Instance attributes

Attributes are data values that belong to objects

  • attributes are usually written as variables that are defined within a class definition
  • these are sometimes called fields or properties of the object they belong to

In the example of class definitions above, the 'name' property is an instance attribute. This means that all objects made from the class will have a name property belonging to them.

Instance methods

Instance methods are methods, or functions, that belong to objects

  • instance methods are usually written as functions that are defined within a class definition
  • these are sometimes called actions or functions of the object they belong to

The following examples add an instance method to the class definition examples above.

Python example

Class definition with instance method:

class Dog:
    age = 0
    name = ""

    def __init__(self, age, name):
        print("A new Dog named " + name + " is born!")
        self.age = age
        self.name = name

    def bark(self):
        print("Woof!")

Instantiate two Dog objects and call each of their instance methods:

dog1 = Dog(3, "Betsie")
dog2 = Dog(0, "Tobik")
dog1.bark()
dog2.bark()

Java example

Class definition with instance method:

class Dog {
    public int age = 0;
    public String name = "";

    public Dog(int age, String name) {
        System.out.println("A new Dog named " + name + " is born!");
        this.age = age;
        this.name = name;
    }

    public void bark() {
        System.out.println("Woof!")
    }
}

Instantiate two Dog objects and call each of their instance methods:

Dog dog1 = new Dog(3, "Betsie");
Dog dog2 = new Dog(0, "Tobik");
dog1.bark();
dog2.bark();

PHP example

Class definition with instance method:

class Dog {
    public $age = 0;
    public $name = "";

    public function __construct($age, $name) {
        print("A new Dog named " . $name . " is born!");
        $this->age = $age;
        $this->name = $name;
    }

    public function bark() {
        print("Woof!")
    }
}

Instantiate two Dog objects and call each of their instance methods:

$dog1 = new Dog(3, "Betsie");
$dog2 = new Dog(0, "Tobik");
$dog1->bark();
$dog2->bark();

Javascript example

Class definition with instance method:

function Dog(age, name) {
    this.age = age;

    console.log("A new Dog named " + name + " is born!");
    this.name = name;

    this.bark = function() {
        console.log("Woof!");
    }
}

Instantiate two Dog objects and call each of their instance methods:

var dog1 = new Dog(3, "Betsie");
var dog2 = new Dog(0, "Tobik");
dog1.bark();
dog2.bark();

Static attributes

Static attributes belong to the class as a whole, not to any specific instance of that class. This is perhaps best illustrated by an example.

Static methods

Static methods belong to the class as a whole, not to any specific instance of that class.

Getters and setters

  • Methods to get and set the values of instance attributes, respectively.
  • Getters simply return the value of a particular instance attribute
  • Setters set the value of a particular instance attribute, and often impose constraints on what values these attributes can be set to
  • In languages with access control, these methods are often public, while instance attributes themselves are usually private.
    • This upholds the object-oriented programming ideal of abstraction, since the internal instance variables are "hidden" from view from a perspective external to the given class.

Python example

Class definition with setter method:

class Dog:
    age = 0
    name = ""

    def __init__(self, age, name):
        print("A new Dog named " + name + " is born!")
        self.age = age
        self.name = name

    def bark(self):
        print("Woof!")

    def setBreed(self, breed):
        self.breed = breed

    def getBreed(self):
        return self.breed

Instantiate two Dog objects and call each of their instance methods:

dog1 = Dog(3, "Betsie")
dog2 = Dog(0, "Tobik")
dog1.bark()
dog2.bark()
dog1.setBreed('German Shepherd')
dog2.setBreed('Poodle')
if dog1.getBreed() == dog2.getBreed():
    print("The dogs are of the same breed")

Java example

Class definition with setter method:

class Dog {
    private int age = 0;
    private String name = "";
    private String breed;

    public Dog(int age, String name) {
        System.out.println("A new Dog named " + name + " is born!");
        this.age = age;
        this.name = name;
    }

    public void bark() {
        System.out.println("Woof!")
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getBreed() {
        return this.breed;
    }
}

Instantiate two Dog objects and call each of their instance methods:

Dog dog1 = new Dog(3, "Betsie");
Dog dog2 = new Dog(0, "Tobik");
dog1.bark();
dog2.bark();
dog1.setBreed('German Shepherd');
dog2.setBreed('Poodle');
if (dog1.getBreed().equals(dog2.getBreed())) {
    System.out.println("The dogs are of the same breed");
}

PHP example

Class definition with setter method:

class Dog {
    private $age = 0;
    private $name = "";

    public function __construct($age, $name) {
        print("A new Dog named " . $name . " is born!");
        $this->age = $age;
        $this->name = $name;
    }

    public function bark() {
        print("Woof!")
    }

    public function setBreed($breed) {
        $this->breed = $breed;
    }

    public function getBreed() {
        return $this->breed;
    }
}

Instantiate two Dog objects and call each of their instance methods:

$dog1 = new Dog(3, "Betsie");
$dog2 = new Dog(0, "Tobik");
$dog1->bark();
$dog2->bark();
$dog1->setBreed('German Shepherd');
$dog2->setBreed('Poodle');
if ($dog1->getBreed() == $dog2->getBreed()) {
    print("The dogs are of the same breed.");
}

Javascript example

Class definition with setter method:

function Dog(age, name) {
    this.age = age;

    console.log("A new Dog named " + name + " is born!");
    this.name = name;

    this.bark = function() {
        console.log("Woof!");
    }

    this.setBreed = function(breed) {
        this.breed = breed;
    }

    this.getBreed = function() {
        return this.breed;
    }
}

Instantiate two Dog objects and call each of their instance methods:

var dog1 = new Dog(3, "Betsie");
var dog2 = new Dog(0, "Tobik");
dog1.bark();
dog2.bark();
dog1.setBreed('German Shepherd);
dog2.setBreed('Poodle');
if (dog1.getBreed() == dog2.getBreed()) {
    console.log("The dogs are of the same breed.");
}

More complex examples in Java

Dog example

This program consists of two files: Dog.java and TestDog.java

Dog.java

package edu.nyu.cs.fb1258;

/**
 * Definition of the Dog class.  Models a real dog in code.
 *
 * @author Foo Barstein
 * @version 1.0
 *
 */
public class Dog {

	//properties (a.k.a. data fields) of any dog object
	public String furType;
	public boolean hasTail = true; //by default, our Dogs have tails
	private String name;
	public int age = 0; //by default, our Dogs are pups
	public int gender;
	
	//define the available genders for any given dog
	//static properties belong to the class, not to any specific object
	public static final int MALE = 0;
	public static final int FEMALE = 1;
	
	/**
	 * Getter method for the name property
	 * @return the name of this dog
	 */
	public String getName() {
		return this.name;
	}
	
	/**
	 * Setter method for the name property.  All names except "Randy" are  allowed.
	 * @param name The name to give the dog
	 */
	public void setName(String name) {
		//allow all dog names except randy
		if (!name.equals("Randy")) {
			this.name = name;			
		}
	}
	
	/**
	 * Setter method for the hasTail property of any given Dog object.  Sets it  to true.
	 */
	public void makeTail() {
		this.hasTail = true;
	}
	
	/**
	 * Setter method for the hasTail property of any given Dog object.  Sets it  to false.
	 */
	public void removeTail() {
		this.hasTail = false;
	}	

	/**
	 * Setter method for the gender property of any given Dog object.  Allows  gender to be set to either 0 or 1, which are represented in this class as  two static constants called MALE and FEMALE.
	 * @param gender
	 */
	public void giveGender(int gender) {
		//validate to make sure the gender is one of our accepted genders
		if (gender == Dog.MALE || gender == Dog.FEMALE) {
			this.gender = gender;
		}
	}
	
	/**
	 * Method to simulate fetching for any given Dog object.
	 * @return randomly returns either true or false, indicating whether  fetching was successful
	 */
	public boolean fetch() {
		double rand = Math.random();
		if (rand > 0.5) {
			System.out.println(this.name + " fetched the stick");
			return true;
		}
		else {
			System.out.println(this.name + " conscientiously objected to your  command to fetch the stick");
			return false;
		}
	}
	
	/**
	 * No-args constructor.  All Dog properties remain with their default  values, if any.
	 * 
	 */
	public Dog() {
		System.out.println("You created a new generic dog");
	}
	
	/**
	 * Constructor that sets the dog's name and age
	 * @param name The name to give it
	 * @param age The age to give it
	 */
	public Dog(String name, int age) {
		this.name = name;
		if (age >= 0) {
			this.age = age;			
		}
		System.out.println("You created new dog with the name " + this.name + "  and age " + this.age);
	}
	
	/**
	 * Constructor that sets a dog's name, age, gender, and hasTail properties.
	 * @param name The name to give the Dog
	 * @param age The age to give the Dog
	 * @param gender The gender to give the Dog: either Dog.MALE or Dog.FEMALE
	 * @param hasTail Boolean value representing whether this dog has a tail or  not
	 */
	public Dog(String name, int age, int gender, boolean hasTail) {
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.hasTail = hasTail;
		System.out.println("You created new dog with the name " + this.name + ",  age " + this.age + ", gender " + this.gender + " and has a tail is " +  this.hasTail);
	}
	
}


TestDog.java

package edu.nyu.cs.fb1258;

/**
 * Class that instantiates a few objects from our Dog class and tests them out.
 * @author Foo Barstein
 *
 */
public class TestDog {

	public static void main(String[] args) {
		//create a new Dog object using the no-args constructor
		Dog fluffy = new Dog();
		fluffy.setName("Fluffy");
		fluffy.giveGender(Dog.FEMALE);
		fluffy.fetch();
		
		//create a new Dog object using one of the overloaded constructors
		Dog spot = new Dog("Spot", 2);
		spot.removeTail();
		spot.fetch();
		System.out.println("This dog is called " + spot.getName());
		
		//create a new Dog object using another of the overloaded constructors
		Dog zeke = new Dog("Zeke", 14, Dog.MALE, true);
		zeke.setName("Sheila");

	}
	
}


Saxophone example

This program consists of two files: Saxophone.java and TestTheSaxophone.java.

Saxophone.java

/**
 * Model of a Saxophone, including a few attributes and methods necessary to use a Saxophone to play free jazz like Eric Dolphy.
 * Listen to http://www.youtube.com/watch?v=DPHnvZBpsSk for an example of a squeaky saxophone in reality.
 *
 * @author Foo Barstein
 * @version 0.2 
 */

package edu.nyu.cs.fb1258;

public class Saxophone {

	/**
	 * range can be either alto or tenor
	 */
	private String range = "alto";

	/**
	 * flag to indicate whether this is an electric saxophone or not.
	 */
	private boolean electric = false;
	
	/**
	 * All notes that it is possible to play on saxophones of this type.
	 */
	private String[] allowedNotes = {
			"A", "A#", "Ab",
			"B", "B#", "Bb",
			"C", "C#", "Cb",
			"D", "D#", "Db",
			"E", "E#", "Eb",
			"F", "F#", "Fb",
			"G", "G#", "Gb"
	};

	/**
	 * Getter method for electric attribute
	 */
	public boolean getElectric() {
		return electric;
	}
	
	/**
	 * Setter method for electric attribute
	 * @param isElectric Boolean indicates whether this saxophone is electric or not.
	 * @return void no return value
	 */
	public void setElectric(boolean isElectric) {
		electric = isElectric;
	}
	
	/**
	 * Play a note on this saxophone.  Notes that are not possible to play on this sax will result in a squeak.
	 * @param note String indicates which note to play.
	 * @return void no return value
	 */
	public void playNote(String note) {
		boolean isAllowed = validateNote(note);
		if (isAllowed) {
			System.out.println("bleep on " + range + "sax in " + note);			
		}
		else {
			makeSqueak();
		}
	}

	/**
	 * Make a squeak on this saxophone.
	 * @return void no return value
	 */
	public void makeSqueak() {
		System.out.println("squeak!");
	}	

	/**
	 * Check whether a given note is possible to play on this saxophone.
	 * @param note String indicates which note to validate
	 * @return boolean true or false depending on whether this note can be played on this sax
	 */	
	private boolean validateNote(String note) {
		boolean isAllowed = false;
		for (int i=0; i<allowedNotes.length; i++) {
			if (allowedNotes[i].equals(note)) {
				isAllowed = true;
			}
		}
		return isAllowed;
	}
	
	/**
	 * Default constructor
	 */	
	public Saxophone() {
		System.out.println("making a new " + range + " sax...hold on!");
	}
	
	/**
	 * Overloaded constructor sets the type of the saxophone when an object is instantiated.
	 * @param saxType String to indicate what type of sax to create: electric or analog.
	 */	
	public Saxophone(String saxType) {
		if (saxType.equals("digital") || saxType.equals("electric") || saxType.equals("electronic")) {
			electric = true;
		}
		else {
			electric = false;
		}

		System.out.println("making a new " + range + " sax...hold on!");
	}

	/**
	 * Overloaded constructor sets the type and range of the saxophone when an object is instantiated.
	 * @param saxType String to indicate what type of sax to create: electric or analog.
	 */	
	public Saxophone(String saxType, String saxRange) {
		if (saxType.equals("digital") || saxType.equals("electric") || saxType.equals("electronic")) {
			electric = true;
		}
		else {
			electric = false;
		}

		if (saxRange.equals("tenor")) {
			range = "tenor";
		}
		else {
			range = "alto";
		}

		System.out.println("making a new " + range + " sax...hold on!");

	}

	
}

TestTheSaxophone.java

/**
 * Program exhibits how to instantiate an object from the Saxophone class and use some of its methods.
 * A main method kick-starts the program.
 *
 * @author Foo Barstein
 * @version 0.2 
 */

package edu.nyu.cs.fb1258;

public class TestTheSaxophone {

	public static void main(String[] args) {

		Saxophone sax1 = new Saxophone(); //create a new Saxophone object
		sax1.playNote("A#"); //calling an instance method
		sax1.playNote("Z");
		sax1.playNote("Bb");

		sax1.setElectric(true); //call the object's setter method for the electric property
		
		//use the getter method to find out some info about this object
		if (sax1.getElectric()==true) {
			System.out.println("This is an electric saxophone");
		}
		else {
			System.out.println("This is an analog saxophone");
		}
		
	} //main

} //class

What links here