Chapter 2
Chapter 2
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
MARCH 1, 2025
DEFINING CLASS
A class--the basic building block of an object-oriented
language such as Java--is a template that describes the data
and behavior associated with instances of that class.
Syntax:
[modifier] type name [=default_value];
Where:
Modifier – optional, can be public, private, protected, final, static
Type – can be a class name or a primitive data type
Name – any valid identifier
Default value – optional initial value
Example of Declaring Attributes
private boolean isReady;
final String message = “Hello”;
int x = 10;
Static Attributes
• Class variables
• Allocated once regardless of how many objects are created.
• Can be accessed even without creating an object
ClassName.staticAttribute
amt = BankAccount.minBalance;
Were
modifier – can carry a number of different modifiers
returnType – can be any data type (including void)
name – can be any valid identifier
parameterList – list of parameters separated by commas. Each item in the
parameter list should have the form: type parameterName
Methods name should be in camel case as a convention
Parameters and Arguments,
Methods, Constructor
Return Values
To return a value
For example,
return;
Getter Methods
Used to read values from our attributes (instance/static)
Returns the value of an attribute using the return keyword.
Usually written as: getNameOfAttribute()
Example:
Class BankAccount {
String name;
:
String getName() {
return name;
}
}
Setter Methods
Used to write or change values of attributes
Written as: setNameOfInstanceVariables(newValue)
The parameter’s type should be the same as the attribute
being modified.
Always returns void
Example:
Class BankAccount {
String name;
:
void setName (String newName) {
name = newName;
}
}
Multiple return Statements
You can have multiple return statements for a method as long as they are not on
the same block
You can also use constants to return values instead of variables
Class MyClass {
int num = 0;
Class MyClass {
int a;
void myMethod() {
int b;
//some code
}
}
Variable Scope Example
class MyClass {
void myMethod(int arg) {
for (int i=0; i<arg; i++) {
//some code
}
if (true) {
int j = 10;
//some code
}
}
}
Scope of a Variable
When declaring variables, only one variable with a given
identifier or name can be declared in a scope.
That means that the following declaration will result to an error:
{
int test = 10;
int test = 20;
}
Attributes Vs. Local Variables
Attributes
Declared within the class scope
Automatically initialized
Local Variables
Declared within the method
Requires explicit initialization
Common Pitfall
Using an uninitialized local variable will cause an error.
class MyClass {
int a;
void myMethod() {
int b;
System.out.println(b);
}
}
this REFERENCE
You can also use the this reference if you want to pass the
calling instance as a parameter to a method.
this REFERENCE
Example
class BankAccount {
int number;
You can also use the this reference if you want to pass the
calling instance as a parameter to a method.
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
Defining and using a multiple class
class Bar {
// Secondary class
}
Note:
When declaring multiple classes in a single file, it is
important to note that the classes must be declared in the
same order as they are used in the program. This is because
the compiler reads the classes in the order they are
declared, and if the classes are not declared in the correct
order, the program will not compile correctly.
Accessing Member Variables
When two or more classes are defined in a Java program,
member variables can be accessed across those classes.
This can be done using either the public or protected
keywords to indicate the visibility of the variable. If a variable
is declared as public, then it can be accessed from any
other class in the program; however, if it is declared as
protected, then it can only be accessed from within its own
class or from subclasses.
Accessing Member Variables
Member variables can be accessed across classes using
visibility modifiers:
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
// Method body;
}
Parts of Method
1. Modifiers:
➢ Tells the compiler how to call the method
➢ Defines the access type of the method
2. Return Types:
➢ The data type of the value the method returns
➢ The return type void when no value is returned
Parts of Method
1. Modifiers:
➢ The actual name of the method
➢ Method name and the parameter list together constitute
the method signature
2. Return Types:
➢ When a method is invoked, a value is passed to
parameter
➢ This value is referred to as actual parameter or argument
➢ The parameter list refers to the type, order, and number of
the parameters.
Parts of Method
1. Modifiers Body
➢ The method body contains a collection of statements that
define what the method does
Method Overloading
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
Constructors
What is Constructors?
• Rules:
✓ When using the this() constructor call, it must be the
first statement in a constructor.
✓ It can only be used in a constructor definition.
this() CONSTRUCTOR CALL
FINALIZERS
• DataAccessObject() {
• conn = DriverManager.getConnection();
• }
• …
• public void finalize() {
• conn.close();
• //perform cleanup procedures
• }
• }
Enum TYPES
To declare a class with attributes representing days of the week
This, however is not type safe. For example, nothing prevents you from writing:
int someday = 99; // No error
Example:
Day today = Day.Monday;
Day anotherDay = 2; // ERROR
System.out.println(today); // MONDAY
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
import java.util.scanner
import java.util.*
In the above program, the * denotes all the classes from the
util package. Along with other classes, it loads the date class
as well. The date class displays the current date and time.
Importing Packages
These two are essentially the same.
import java.util.Date;
import java.lang.*;
class Appointment {
Date when;
String where;
}
______________________________________________________
class Appointment {
java.util.Date when;
String where;
}
Use Complete Qualified Name
java.net.InetAddress
ipAddress=java.net.InetAddress.getLocalHost();
package packageName.subpackage;
Coding Conventions
The three top-level elements must appear in the following
order:
• Package declaration
• Import statements
• Class definitions
Class path variable and how classes are
found
• Tells the Java compiler where to look for packages, not
classes.
• Assuming your working directory is C:\321, and you
have a BankAccount class in the package com.banco
ITRACKC1
CHAPTER 2
Defining Own Classes And The Use Of
Methods
• Example
Class
{
method
{
declare variable
}
}
Example– Local Variable
Variable Type – Instance Variable
▪ It declare inside of a class but outside of methods.
▪ This variable can be access by any methods.
▪ By Creating object for a class, we can access this variable
from main methods.
Class
{
declare variable
method
{
// can use var
}
▪ }
Example– Instance Variable
Variable Type – Class/Static Variable
▪ Variable declared inside of class but outside of methods with
static keyword.
▪ Static variables are stored in the static memory.
▪ Static variables can be accessed by static methods or
constructors
Class
{
declare variable
constructor
{
// can use var
{
//can use var
}
}
Example– Class/Static Variable
CATANDUANES STATE UNIVERSITY
COLLEGE OF INFORMATION AND COMMUNICATIONS TECHNOLOGY
ITRACKC1
THANK YOU