Using Methods, Classes, and Objects
Student Learning Objectives
1. Creating Methods
2. Adding Parameters to Methods
3. Multiple Parameters
4. Methods that Return Values
5. Class Concepts
6. Creating a Class
7. Declaring objects and using their methods
8. Classes are data types
Methods - a method is a program module that contains a series of
statements that carries out a task. Any class can contain an unlimited
number of methods and each method can be called an unlimited number of times.
You call a method to use it.
a. Method header- declaration provides information about how other methods can interact with it. Contains the following:
(1) Optional access specifier - Public (any class can use it), Private, Protected, or package(left unspecified)
(2) Static - no objects need to be created
b. Method body contained in curly braces and contains the statements that carry out the work of the method. A method's body is called its implementation.
c. Implementation - an empty method is called a stub.
d. Return type - a method might return a value, or send it back to its calling method. The method's return type is the data type of the returned value. A method that returns no value is called a void.
e. Method name -any legal identifier.
f. Parentheses - might contain data to be sent to the method.
g. You cannot place a method inside of another method.
h. public static void nameAndAddress() -(public) this method can be access by any class, (static) no objects need to be created, (void) returns nothing. (nameAndAddress) method name, () are empty since it returns nothing.
i. The order in which methods are placed in a class is immaterial. It is the order in which the methods are called that determine program execution.
j. Two classes in a project cannot have the same name. When referring to a method in a different class it must have the class name. For example:
first(class name).nameAndAddress() references the method nameAndAddress() contained in the first class.
k. Not every class needs a main method but every project does.
2. Adding Parameters
a. Data items used in a call to a method are called arguments. When the method receives the data they are called parameters.
b. Implementation hiding is a key principle in OOP which is just the encapsulation of method details within a class.
public class demoRaise
public static void main(String args)
System.out.println("demonstrating some raises");
predictRaise(400.00); //this is the first call to predictRaise using 400.00 as the argument
predictRaise(mySalary); //this is the second call to predictRaise using mySalary(200.00) as the argument
predictRaise(moneyAmount); //this is the third call to predictRaise using moneyAmount(800.00) as the argument
public static void predictRaise(double moneyAmount)-here moneyAmount is declared as a local variable and is the argument to predictRaise.
double newAmount; //here new amount is declared as a local variable
final double RAISE=1.10; //here RAISE is declared as a local constant
newAmount=moneyAmount * RAISE;
System.out.println("With raise, salary is " + newAmount);
3. Multiple Parameters - declaration for a method that receives two or more parameters must list the data type for each. Additionally, arguments passed to the method must be passed in the correct order.
public class computeCommission
public static void main(string args)
computeCommission(value, commRate, vType); first call to computeCommission-passes 23000,0.08,S to method
computeCommission(40000, 0.10,'L'); second call to computeCommission - passes 40000,0.10,L to method
public static void computeCommission(int value, double rate, char vehicle) accepts parameters from call
double commission; declares variable commission
commission=value * rate; in first call value=23000 and rate = .08 and char=S, in second call value=40000 and rate= .10 and char=L
System.out.println("\nThe " + vehicle + " type vehicle is worth $" + value);
System.out.println("With " = (rate *100) + "% commission rate, the commission is $" + commission);
The S type vehicle is worth $23000
With 8.0% commission rate, the commission is $1840.0
The L type vehicle is worth$40000
With 10% commission rate, the commission is $4000.0
4. Methods that Return Values
Note that methods end when statements are completed, or an exception is noted, or reaches a return statement. A method can return only one value which can be primitive data or a class type. All methods except void methods require a return statement. Any code placed after the return in the method is called dead code and will not compile. A return statement causes a method to end and the programs logic to return to the calling method, and frequently send a value back to the calling program. Any statements after the return in a method are unreachable and cause a compiler error. The return statement causes a method to end. The return type for a method known as method's type.
a. public static void nameAndAddress(_) - method is public and returns no value so it is type void.
b. public boolean workedOvertime() - method is public and return a Boolean value and so it is type Boolean .
c. A method can return a class type in addition to returning of one of the primitive types.
d. All methods except void methods require a return statement that returns a value of the appropriate type.
e. You cannot place any statements after the return statement.
static double predictRaise(double moneyAmount)
final double RAISE = 1.10;
newAmount=moneyAmount * RAISE;
return newAmount: //The return statement cause a value to be sent from a called method back to the calling method.
f. Chaining Method Calls. Any method might call any number of other methods, which may have calls to other methods.
5. Class Concepts- An object is an instantiation of a
class.(tangible example of a class)
a. Useful because of its reusability. Objects gain their attributes from their classes and all objects have predictable attributes because they are members of certain classes. The data components of a class are often referred to as the instance variables of that class. Class data attributes are often called fields to help distinguish them from other variables you might use.
b. You can call an application or class that instantiates objects of another prewritten class. A class is an application because it contains a public static void main() method. It is the starting point for any application.
c. A Java application can contain only one method with the header public static void main(String args). If more than one, it will not compile.
6. Creating a class
a. Optional access specifier - public, private final, abstract, or strictfp. Public will be used for most classes.
b. Keyword Class - Example - public class
c. Choose any legal identifier for the name of the class. Example: public class employee
d. Access levels for member variables and methods: Private, Public, protected, and package.
e. Assigning public-classes makes them accessible by all objects and can be used as the basis of other classes-extended,
f. Assigning private access to a field means that no other classes can access the fields values and only methods of the same class are allowed to set, get, or otherwise use private variables. Often referred to as Information Hiding.
g. Data field static or not. Once per class is static, more than once per object is not static. Data fields are variables you declare within a class but are outside of any method. Data fields are most often private and not static. Data fields are most often made public when they are static and final.
In Java, static is a keyword. It also can be used as an adjective
There is no keyword for nonstatic items. Nonstatic is the default
Static fields in a class are called class fields
Nonstatic fields in a class are called instance variables
Static methods in a class are called class methods
Nonstatic methods in a class are called instance methods
When you use a static field or method. You do not use an object: for example: JOptionPane.showDialog();
When you use a nonstatic field or method, you must use an object; for example: system.out.println();
When you create a class with a static field and instantiate 100 objects, only one copy of that field exists in memory.
When you create a class with a nonstatic field and instantiate 100 objects, then 100 copies of that field exist in memory.
When you create a class with a static field and instantiate 100 objects, only one copy of the method exists in memory and the method does not receive a this reference.
When you create a nonstatic method in a class and instantiate 100 objects, only one copy of the method exists in memory, the method receives a this reference that contains the address of the object currently using it.
Static class variables are not instance variables. The system allocates memory to hold class variables once per class, no matter how many instances of the class you instantiate. The system allocates memory for class variables the first time it encounters a class, and every instance of a class share the same copy of any static class variables.
The instance fields and methods are notnstatic. The sytem allocates a separate memory location for each nonstatic field in each instance.
Methods that set values are called mutator methods; methods that retrieve values are called accessor methods.
h. When you create a class like employee you can compile it and locate typographical errors but you can not execute it because it does not contain a main() method. Employee is intended to be used as a data type for objects within other applications. Example:
public class Employee
private int empNum; //Employee class contain one private data field and two public methods, which are notstatic.
public int getEmpNum() //this method retrieves the value
public void setEmpNum(int emp) //this method provides a value for empNum
7. Declaring objects and using their methods
a. When declaring primative data types, it is not necessary to allocate memory. When declaring non-primative data types it is necessary to use the new operator to allocate memory for the non primative data type.
For Example: referencing the class employee
Employee someEmployee = new Employee();
Employee is the Class, someEmployee is the reference to the object - memory address of stored data , = assignment operator, new allocates memory, Employee() is a constructor method that creates and initializes objects. The name of the consturctor is always the same as the name of the class whose object it contructs.
b. After an object has been instantiated, its methods can be accessed using the object identifier, a dot and a method call.
Employee clerk = new Employee();
c. If your class is not in the same folder as your project you would need to use the import statement at the top of the file.
d. A default constructor is one that requires no arguments and is created automatically by the Java compiler for any class you created.
1. Numeric fields are set to 0(zero)
2. Character fields are set to Unicode '\u0000'
3. Bollean fields are set to false.
4. Fields that are objects themselves (string fields) are set to null. Any constructor you write must have the same name as the class it constructs and cannot have a return type. When you write a constructor for a class, you no longer have access to the automatically created version.
8. Understanding that classes are data types. - A class can be called a programmer-defined data type, a type that is not
built into the language.
a. When you declare a primitive variable or instantiate an object from a class, you provide both a type and an identifier.