Classes and Methods in Java
Chapter 5: Defining Classes and Methods
Objectives
- Describe the concepts of class and object.
- Define a Java class and its methods.
- Describe and define instance variables.
- Create objects.
- Describe passing and returning objects to/from methods.
Revision!
- Create and initiate 1-D and 2-D arrays.
- Traverse an array.
- Pass a single element to methods (pass by value).
- Pass the entire array to a method (pass by reference).
- Return the entire array from a method.
Objects, Classes, and Instances
Class
- A class is like a plan or a blueprint for constructing objects. It defines what an object of that class will look like and what it can do.
- You need to create an object of a class before you can program the class tasks or methods.
Class Attributes
- A class specifies the attributes, or data, that objects of the class could have.
- These attributes in the class definition do not contain actual data (numbers or strings).
*Objects hold the real data for these attributes.
Class Methods
- A class specifies what actions the objects can take and how they accomplish those actions.
- These actions are described within the class by methods.
- All objects of any class will have the same methods.
Object
- Objects in a program can represent:
- Real-world objects (e.g., automobiles, houses, employee records).
- Abstractions (e.g., colors, shapes, words).
- A Java program consists of objects that:
- Can be of the same class types.
- Interact with one another.
Object - Example
- To instantiate a class means to create an instance (object) of that class.
Key Observations About Classes and Objects
- Classes are used to create objects.
- A class is created once, and then multiple objects of that class can be created.
- Each object satisfies the class definition.
- Each object has a name (e.g., patsCar, suesCar, ronsCar).
- In a Java program, the data type of these objects (variables) is the class type (e.g., Automobile).
- The class itself has no specific values for attributes.
- The objects have values for their attributes.
Declaring Classes
- Syntax:
java Access-specifier class ClassName { // class fields and methods }Access-specifier: Defines which access other classes might have to this class (e.g.,public).class: A Java keyword that must be part of the class declaration.ClassName: A user-defined name of the class and must be a valid Java identifier. Start the class name with a capital letter and follow the CamelCase syntax. Usually, class names are nouns.- Each class has a body that is enclosed between
{}. - The class’s body might include constants, fields, methods, etc.
Class Body
- General class structure:
java public class ClassName { Constants/Variables Constructors Methods including main() } - A class can have two members:
- Fields (data/variables/attributes).
- Methods.
- We explicitly define both members within the class body.
Class Files in Java
- Each Java class definition is usually placed in a file by itself.
- The file name is the same as the name of the class and ends with
.java(e.g.,Automobile.java). - Classes can be compiled separately.
- It's helpful to keep all class files used by a program in the same directory (folder).
- The
mainmethod is placed in a test class, often referred to as the "driver" program or class.
Class Body: Variables or Attributes
public class ClassName {
Constants/Variables
}
Instance Variables
- Instance variables are the variables that objects have (contain).
- Their values describe the objects’ state.
- An instance variable means it will occur once per instance of a class (i.e., it's unique for each object of that class).
- Every time a new instance of the class (object) is created, the system will allocate instance variables of its own for each instance of the class.
- They are associated with objects.
- Instance variables must be declared within the class body, but not within the body of a method.
- Variables declared within the body of a method are local to that method and cannot be accessed outside the method’s body!
Instance Variables - Syntax
- Syntax:
java access-specifier data-type variableName;access-specifier: ispublic.data-type: Could be a primitive or non-primitive data type.variableName: Has to be a valid Java identifier.
Static (Class) Variables
- These are variables where each object of a class does not need its own separate copy.
- When objects of a class containing static variables are created, all the objects of that class share one copy of those variables.
- All objects of the class share the same piece of data.
- Static variables must be declared within the class body, but not within the body of a method!
Static (Class) Variables - Syntax
Syntax:
access-specifier static data-type variableName;access-specifier: ispublic.static: An access modifier that is used to declare variables that belong to a class.data-type: Could be a primitive or non-primitive data type.variableName: Has to be a valid Java identifier.
Instance vs. Class Variables
- Both types of variables are accessible anywhere in a class; this includes within methods because they have class scope.
Instantiating Classes (Creating Objects)
Syntax:
className objectName = new classConstructor();className: Is the class name that we want to instantiate.objectName: Is the object name and has to be a legal Java identifier.new: Is a unary operator in Java that we use to create objects of a class. It then returns the memory address of the object and assigns it to the variable!ClassConstructor(): Is a special kind of method used that initializes the object; constructors always have the same name as the class!
Another way to create an object:
className objectName; // object is not created yet! objectName = new classConstructor();
How to Access or Use Instance Variables
- Refer to one of the instance variables by writing the object name followed by a dot and then the instance variable’s name.
- Refer to one of the class variables by writing the class name followed by a dot and then the static variable’s name.
Constructors
- A special method called when an instance of a class (object) is being created with the
newoperator. - Constructors are used to create objects and initialize values of instance variables.
- You cannot use an existing object to call a constructor.
- Constructors could have:
- Parameters (parameterized constructors): To specify initial values of fields or attributes.
- No parameters (no-argument constructors): They provide the default values to the object upon its creation such as 0 and
null.
- Constructors may have multiple definitions (headings), but each with different numbers or types of parameters.
- It is called constructors overloading which refers to multiple constructors for the same class
- Java compiler differentiates between them based on the parameter list, types of the parameters, and order of the parameters.
- Constructors have the same name as the class.
- Generally, at least one constructor for a class is present.
- If none was explicitly declared, then JVM injects a default constructor for you.
- A default constructor has no parameters.
- If you do define a constructor, Java will not automatically define a default constructor.
- What differentiates constructors from other class’s methods:
- They must take the class name within which it is defined.
- They do not return any type, not even
void. - They are called only once when we create objects of that class.
Defining Constructors - Syntax
- Syntax:
java Access-Specifier ClassName(parameters list) { // constructor body }Access-Specifier: Determines the type of access to the constructor. It should bepublic.ClassName: Is the name of the class where the constructor will be defined.parameters list: Is a comma-separated list of variables that a method could receive.
Class Methods
public class ClassName {
Constants
Variables
Constructors
Methods including main()
}
Defining/Declaring Methods - Syntax
Static (Class) Methods
- Class methods belong to a class and NOT to an instance of a class.
- They are known as static methods.
- Class methods must be declared within the body of the class.
- They are typically declared after class variables in the class.
- They are created using the keyword
staticbefore the method name. - Static methods can be called without creating an object of the same class.
- They can be invoked by using the class name.
- They can access static class variables and change their values.
Instance (Non-Static) Methods
- A non-static method defined in the class is known as an instance method.
- They are used to modify objects’ state (instant/non-static variables).
- Known as Accessors and Mutators.
- Before calling or invoking instance methods, we must create an object of its class.
- They are created WITHOUT using the keyword
staticbefore the method name.
Invoking Non-Static Methods
- Syntax:
java ObjectName.methodName(argument list);ObjectName: Is the name of the object of the same class type as the method.methodName: Is the name of the method that we want to call.argument list: Is a list of variables or expressions that will be sent to the method by the caller.
- Calling a non-static method that returns a quantity.
- Use anywhere a value can be used –assignment statements-.
- Example:
number = keyboard.nextInt();
- Calling a non-static
voidmethod.- Write the invocation statement followed by a semicolon.
- The resulting statement performs the action defined by the method.
- Example:
System.out.println("Hello World!");
Static VS. Non-Static Methods
| Feature | Static (class) | Non-Static (instance) |
|---|---|---|
| Declaration | Declared with keyword static | Declared without keyword static |
| Calling / Invocation | Could be invoked using class name | Must be invoked by an object of the same class |
| Accessing Variables | Can access static variables and methods | Can access static variables and methods |
| Accessing NON-Static Variables | Cannot access instance variables and methods directly – must create an object to use them – | Can access instance variables and methods directly – no need to create an object |
Using this keyword | Can NOT use “this” keyword since there is no instance for this to refer to! | Can use “this” keyword |
The Keyword this
- When we want to refer to instance variables outside the class, we must use:
- Name of an object of the same class, followed by a dot and the name of the instance variable.
- But, when we are inside the class, we could use:
- Name of the instance variable alone without the object!
- So, to refer to the object for that instance variable, we could use the name
this. - The keyword
thisstands for the receiving object.
Variables of a Class Type (Objects)
- All variables are implemented as a memory location.
- Data of primitive type stored in the memory location assigned to the variable.
- Variable of class type contains a memory address (reference) of the object named by the variable.
- A memory address is a number, but it is not the same kind of number as an
intvalue. - Do not try to treat it as an ordinary integer!
Dangers of using == with objects
- When you compare two objects using the
==operator, you are checking to see whether they have the same address in memory! - You are not testing for what you would intuitively call equality!
Defining an equals Method
- We must write a method for a given class which will make the comparison as needed.
- We could compare the values of the instance variables of objects!
Passing and Returning Objects to/from Methods
Passing Parameters by Reference
- The pass by reference method passes the parameters as a reference (memory address) of the original argument.
- The called method does not create its own copy; rather, it refers to the original address of where the values are kept.
- Hence, the changes made in the called method will be reflected in the original parameter as well.
- Similar to the use of a parameter of class type.
- The memory address of the actual parameter is passed to the formal parameter.
- The formal parameter may access public elements of the class.
- The actual parameter thus can be changed by class methods.
Return Class Type Methods
- A method in Java could return a reference (memory address) of the original parameter to the caller.
- Similar to passing a parameter by reference to a method, the caller of the method could make changes to the values of the parameters since the method returns an address not a value!
Case Study: Employee Class
- PART ONE:
- Create a class called
Employeethat includes three instance variables: a first name (String), a last name (String), and a monthly salary (double). - The class also has two methods, namely
calculateRaiseanddisplayInfo. - The method
calculateRaisewill calculate a 10% raise of the salary and display it on the screen. - The method
displayInfoprints/displays the employee's information.
- Create a class called
- PART TWO:
- Create a driver/test program named
EmployeeTestthat demonstrates classEmployee’s capabilities. It has themainmethod! - Create two
Employeeobjects and display each object’s yearly salary. Then give eachEmployeea 10% raise and display eachEmployee’syearly salary again.
- Create a driver/test program named
- Notes:
- Class
Employeehas nomainmethod! - Both classes
EmployeeandEmployeeTestmust be in the same package!
- Class
Summary
- Classes have:
- Instance variables to store data
- Method definitions to perform actions
- Methods may be:
- Value returning methods
- Void methods that do not return a value
- The keyword
thisused within a method definition represents the invoking object - Local variables defined within a method definition
- Formal arguments must match actual parameters with respect to number, order, and data type
- Formal parameters act like local variables
- A parameter of primitive type is initialized with the value of the actual parameter
- The value of the actual parameter is not altered by the method
- A parameter of class type is initialized with the address of the actual parameter object
- The value of the actual parameter may be altered by method calls
- A method definition can include a call to another method in the same or different class
- The operators
=and==, when used on objects of a class, do not behave the same as they do when used on primitive types. - You usually want to provide an
equalsmethod for the classes you define.