3 - Classes, Objects, Methods
3 - Classes, Objects, 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>
...
}
<member>
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 }
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 {
}
}
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
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.
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.
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,
Class Variable
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
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.
Person2.java
public class Person2 {
public int getAge() { return age; } public void setAge(int personAge) { age = personAge; }
}
All non-primitive types are reference types. A primitive-type variable can store exactly one value of its declared type at a time.
Objects that are referenced may each contain many instance variables and methods.
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.
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.
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.
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.");
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)