You are on page 1of 43

Object Oriented Programming

Objects, Classes and Methods

What is an Object?
Real-world objects: e.g. Car, Book, Person Characteristics of real-world objects: state and behaviour States (attributes) are used to describe an object. e.g. States of a Person - name, age, height, etc. Behaviours are what an object can do. e.g. Behaviours of a Person: walking, talking, eating, etc. Identify some objects around you and observe their states and behaviours.

Software Objects
Software objects have very similar characteristics to real-world objects. Software objects also have a state and behavior. A software object's state is stored in fields (variables) and behavior is shown via methods. Methods operate on the internal state of an object and the object-to-object communication is done via methods.

What is a Class?
A class is a specification (blueprint or pattern and a set of instructions) of how to construct something. Real world examples of specifications:
Engineers use blueprints to build buildings, bridges, etc. Tailors use patterns to make clothes Cooks follow recipes to put together meals

Classes in Java
A Java class is a template for an object you create. Every object you define will follow that pattern. Template for the source code of a class:
class <identifier> {

<member>
...
}

<identifier> - Class Name

<member>

- Fields (Variables) and Methods

Example class
Class header

public class Person { String name; int age; String phone; void sayHello(){ } void givePhoneNumber(){ } }

Fields

Methods

Class body

Methods
A method is a series of statements that carry out a task. Methods provide the actions in Java programs calculations, modify fields, give outputs, etc. Example method declaration:
public double calculateArea (double h, double w) { //do the calculation here }

Required elements of a method declaration:


method's return type, method name, a pair of parentheses, (), a body between braces, {}

In general, method declarations have six components: 1. Modifiers public, private, etc 2. The return type the data type of the value returned by the method, or void if the method does not return a value. 3. The method name any legal identifier. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. e.g. run, calculateAnswer, getFinalData.

4. The parameter list in parenthesis a comma-separated list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. 5. An exception list to be discussed later. 6. The method body, enclosed between braces the method's code, including the declaration of local variables, goes here.

Person.java
public class Person {

public void sayHello(){ System.out.println("Hello"); }


public void sayName(String name){
System.out.println("My name is " + name);

}
}

Creating an Object
A class provides the blueprints for objects. So, an object is created from a class. In Java, the new keyword is used to create new objects. 3 steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type. Instantiation: The 'new' key word is used to create the object. Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
<classname> <identifier> = new <classname>( ); e.g.
Person aPerson = new Person();

Constructor

Invoking (Calling) a Method


Method invocation transfers control from the point in your program where the invocation has been made to the method being invoked. When the method finishes its actions, execution comes back to just after where the invocation was made.

Method Parameters
A method can require one or more parameters that represent additional information it needs to perform its task. (Parameter: Additional information a method needs to perform its task.)
Defined in a comma-separated parameter list Located in the parentheses that follow the method name Each parameter must specify a type and an identifier.

A method call supplies valuescalled argumentsfor each of the methods parameters. The number of arguments in a method call must match the number of parameters in the parameter list of the methods declaration. The argument types in the method call must be consistent with the types of the corresponding parameters in the methods declaration.

e.g. To invoke/call the sayHello method in the Person class: Semicolon


aPerson.sayHello();
Object Identifier Dot Operator Method Identifier Parenthesis

To invoke the sayName method in the Person class:


aPerson.sayName("Mr. Nobody");

Arguments within parenthesis

Testing the Person Class


Class Person is not an application because it does not contain the main method. Cant execute Person; will receive an error message like:
Exception in thread "main" java.lang.NoSuchMethodError: main

Must either declare a separate class that contains a main method or place a main method in class Person. It is better to use a separate class containing the main method to test each new class. Such a class is referred to as a driver class.

PersonTest.java
public class PersonTest {

public static void main (String[] args){ Person aPerson = new Person(); aPerson.sayHello();
aPerson.sayName("Mr. Nobody");

}
}

Variables in Java
A class can contain any of the following variable types.
Local variables Instance variables

Class variables

Local Variables
Variables defined inside
methods,
constructors, or blocks are called local variables.

The variable will be declared and initialized within the method


and the variable will be destroyed when the method has completed.

Local Variables
public int calculate(int a, int b){

int sum;
sum = a + b; return sum; }

Local Variable

Class Variables
Class variables are variables declared
within a class,

outside any method,


with the static keyword. public class SomeClass{

Class Variable

private static String aClassVariable; public void someMethod(){ ... } }

Instance Variables
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or block of that particular class.

Instance Variables
Every instance (i.e., object) of a class contains one copy of each instance variable. Instance variables are typically declared private.
private variables and methods are accessible only to

methods of the class in which they are declared.

Declaring instance private is known as data hiding or information hiding.

Instance Variables
private variables are encapsulated (hidden) in the

object and can be accessed only by methods of the objects class. Prevents instance variables from being modified accidentally by a class in another part of the program. Set and get methods are used to access instance variables.

Set and Get Methods


set and get methods A classs private fields can be manipulated only by the classs methods. A client of an object calls the classs public methods to manipulate the private fields of an object of the class. Classes often provide public methods to allow clients to set (i.e., assign values to) or get (i.e., obtain the values of) private instance variables. The names of these methods need not begin with set or get, but this naming convention is recommended.

Person2.java
public class Person2 {

private int age;

public int getAge() { return age; } public void setAge(int personAge) { age = personAge; }
}

Primitive Types vs. Reference Types


Types are divided into primitive types and reference types. The primitive types are,
boolean byte char short int long float double

All non-primitive types are reference types. A primitive-type variable can store exactly one value of its declared type at a time.

Primitive Types vs. Reference Types


Primitive-type instance variables are initialized by default Variables of types byte, char, short, int, long, float and double are initialized to 0

Variables of type boolean are initialized to false.


You can specify your own initial value for a primitivetype variable by assigning the variable a value in its declaration.

Primitive Types vs. Reference Types


Programs use variables of reference types (normally called references) to store the locations of objects in the computers memory.
Such a variable is said to refer to an object in the program.

Objects that are referenced may each contain many instance variables and methods.

Primitive Types vs. Reference Types


Reference-type instance variables are initialized by default to the value null
null - A reserved word that represents a reference to nothing.

When using an object of another class, a reference to the object is required to invoke its methods.
Also known as sending messages to an object.

Initializing Objects with Constructors


When an object of a class is created, its instance variables are initialized by default. Each class can provide a constructor that initializes an object of a class when the object is created.

Java requires a constructor call for every object that is created.


Keyword new requests memory from the system to store an object, then calls the corresponding classs constructor to initialize the object. A constructor must have the same name as the class.

Initializing Objects with Constructors


By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor.
Instance variables are initialized to their default values by the default constructor.

Can provide your own constructor to specify custom initialization for objects of your class. A constructors parameter list specifies the data it requires to perform its task.

Initializing Objects with Constructors


Constructors cannot return values, so they cannot specify a return type. Normally, constructors are declared public. If you declare any constructors for a class, the Java compiler will not create a default constructor for that class. Therefore, if you want to use the default constructor for such a class, you have to explicitly declare the default constructor.

Person3.java
public class Person3 { private String name; private int age; private String phone; public Person3(){

}
public Person3(String name, int age, String phone){ this.name = name; this.age = age; this.phone = phone; } }

Exercise 1 a
A circle has a radius (type double) Two operations that can be done on the circle are,
Calculate circumference (2 * PI * radius) Calculate area (PI * radius * radius) (Assume PI = 3.14)

The value of the radius can be set. The value of the radius can also be viewed. Write a class to represent the circle object.

Exercise 1 b
A circle has a radius (type double) Two operations that can be done on the circle are,
Calculate circumference (2 * PI * radius) Calculate area (PI * radius * radius) (Assume PI = 3.14)

The value of the radius can be set when the circle is created (using a constructor). If it is not set when the circle is created, then the radius can be set later. The value of the radius can also be viewed. Write a class to represent the circle object.

Exercise 1 c
Write a class to test the Circle class in the previous exercise. Create two circle objects. Do not set the value of the first circles radius when the object is initially created (keep the default value), and set the radius later. Set the value of the second circles radius when the object is created. (It is not necessary to get user input to set the value of the radius; you can hardcode the value.) Display the output to show the radius, area and circumference of the circles

Exercise 2
A class represents a counter that counts 0, 1, 2, 3, 4,.... The name of the class should be Counter. It has one private instance variable representing the value of the counter. It has two instance methods:
increment() adds one to the counter value, and getValue() returns the current counter value.

Write a complete definition for the class, Counter.

Exercise 3
This problem uses the Counter class from the previous exercise. The following program segment is meant to simulate tossing a coin 100 times. It should use two Counter objects, headCount and tailCount, to count the number of heads and the number of tails. Fill in the blanks so that it will do so. Complete the program, run it and get the output.
Counter headCount, tailCount; __________= ______ ______ ( ); __________= ______ ______ ( ); for ( int flip = 0; flip < 100; flip++ ) { if (Math.random() < 0.5) // There's a 50/50 chance that this is true. ______________________ ; // Count a "head". else ______________________ ; // Count a "tail". } System.out.println("There were " + ___________________ + " heads.");

System.out.println("There were " + ___________________ + " tails.");

Exercise 4
Create a class called Employee that includes three pieces of information as instance variablesa first name (type String), a last name (type String) and a monthly salary (type double). Your class should have a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test application named EmployeeTest that demonstrates class Employees capabilities. Create two Employee objects and display the yearly salary for each Employee. Then increase each Employees salary by 10% and display each Employees yearly salary again.

Exercise 5
Create a class called Date that includes three pieces of information as instance variablesa day (type int), a month (type int), and a year (type int). Your class should have a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and a get method for each instance variable. Provide a method displayDate that displays the day, month, and year separated by forward slashes (/). E.g. 29/2/2012 Write a test application named DateTest that demonstrates class Dates capabilities.

Exercise 6 a
Your weight is the amount of gravitational attraction exerted on you by the earth. Since the moons gravity is approximately 0.167 of the earths gravity, on the moon you would weigh only 0.167 times of what you weigh on the earth. Write an application that inputs the users earth weight and outputs his/ her weight on Mercury, Venus, Jupiter, and Saturn. Use the values in the table below.
Planet Mercury Venus Jupiter Saturn Multiply the Earth Weight by 0.4 0.9 2.5 1.1

Exercise 6 b
Write an instantiable WeightConverter class. An instance of this class is created by passing the gravity of an object relative to the earths gravity (see the previous question). For example, the moons gravity is approximately 0.167 of the earths gravity, so we create a WeightConverter instance for the moon as,
WeightConverter moonWeight; moonWeight = new WeightConverter(0.167);

To compute how much you weigh on the moon, you pass your weight on earth to the convert method as
yourMoonWeight = moonWeight.convert(50);

Define the WeightConverter class. Use this class and redo the previous question

Exercise 7
Write an application that computes the total ticket sales of a concert. There are three types of seatings: A, B, and C. the program accepts the number of tickets sold and the price of a ticket for each of the three types of seats. The total sales are computed as totalSales = numberOfA_Seats * pricePerA_Seat + numberOfB_Seats * pricePerB_Seat + numberOfC_Seats * pricePerC_Seat ;

Write this application using only one class, the main class of the program.

Redo the above question by using an instantiable SeatType class. An instance of the SeatType class keeps track of the ticket price for a given type of seat (A, B, or C) and the number of tickets sold for each seat type. (Hint: Create objects called seatA, seatB, and seatC to track the sales)

You might also like