Java Create Class
Java Create Class
Classes
1
Objectives
At the end of the lesson, the student should be able to:
2
Defining Your
Own Class
3
Defining your own classes
● Things to take note of for the syntax defined in this
section:
4
Defining your own classes
● To define a class, we write:
5
Example
public class StudentRecord {
//we'll add more code here later
}
– where,
● public - means that our class is accessible to other classes
outside the package
● class - this is the keyword used to create a class in Java
● StudentRecord - a unique identifier that describes our
class
6
Coding Guidelines
● Think of an appropriate name for your class. Don't just
call your class XYZ or any random names you can think
of.
● Class names starts with a CAPITAL letter - not a
requirement, however.
● The filename of your class must have the SAME NAME
as your class name.
7
Instance Variables
vs.
Static Variables
8
Instance Variables (Properties) vs.
Class (Static) Variables
● Instance Variables
– Belongs to an object instance
– This means that they have the same value for all the
object instances in the same class.
9
Class Variables
● For example,
10
Instance Variables
11
Declaring Properties (Attributes)
● To declare a certain attribute for our class, we write,
12
Instance Variables
public class StudentRecord {
// Instance variables
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
//we'll add more code here later
}
– where,
● private here means that the variables are only accessible within
the class. Other objects cannot access these variables directly.
13
We will cover more about accessibility later.
Coding Guidelines
● Declare all your instance variables right after “public
class Myclass {“
● Declare one variable for each line.
● Instance variables, like any other variables should start
with a SMALL letter.
● Use an appropriate data type for each variable you
declare.
● Declare instance variables as private so that only class
methods can access them directly.
● Encaptulation
14
Static Variables
15
Class (static) variables
public class StudentRecord {
//static variables we have declared
private static int studentCount;
//we'll add more code here later
}
16
Methods
17
Declaring Methods
● To declare methods we write,
<modifier> <returnType>
<name>(<parameter>*) {
<statement>*
}
– where,
● <modifier> can carry a number of different modifiers
● <returnType> can be any data type (including void)
● <name> can be any valid identifier
● <parameter> ::= <parameter_type> <parameter_name>[,]
18
Accessor (Getter) Methods
● Accessor methods
– used to read values from our class variables
(instance/static).
– usually written as:
get<NameOfInstanceVariable>
– It also returns a value.
19
Example 1: Accessor (Getter) Method
public class StudentRecord {
private String name;
:
public String getName(){
return name;
}
}
– where,
● public - means that the method can be called from objects
outside the class
● String - is the return type of the method. This means that the
method should return a value of type String
● getName - the name of the method
20
● () - this means that our method does not have any parameters
Example 2: Accessor (Getter) Method
public class StudentRecord {
private String name;
// some code
21
Mutator (Setter) Methods
● Mutator Methods
– used to write or change values of our class variables
(instance/static).
– Usually written as:
set<NameOfInstanceVariable>
22
Example: Mutator (Setter) Method
public class StudentRecord {
private String name;
:
public void setName( String temp ){
name = temp;
}
}
– where,
● public - means that the method can be called from objects
outside the class
● void - means that the method does not return any value
● setName - the name of the method
● (String temp) - parameter that will be used inside our method
23
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.
24
Example: Multiple return
statements
public String getNumberInWords( int num ){
String defaultNum = "zero";
if( num == 1 ){
return "one"; //return a constant
}
else if( num == 2){
return "two"; //return a constant
}
//return a variable
return defaultNum;
}
25
Static Methods
26
Static methods
public class StudentRecord {
private static int studentCount;
public static int getStudentCount(){
return studentCount;
}
}
– where,
● public- means that the method can be called from objects
outside the class
● static-means that the method is static and should be called by
typing,[ClassName].[methodName]. For example, in this case,
we call the method StudentRecord.getStudentCount()
● int- is the return type of the method. This means that the method
should return a value of type int
● getStudentCount- the name of the method
● ()- this means that our method does not have any parameters
27
Coding Guidelines
● Method names should start with a SMALL letter.
● Method names should be verbs
● Always provide documentation before the declaration of
the method. You can use Javadocs style for this. Please
see example.
28
When to Define Static Method?
● When the logic and state does not involve specific object
instance
● Computation method
● add(int x, int y) method
● When the logic is a convenience without creating an object
instance
● Integer.parseInt();
29
Source Code for StudentRecord
class
public class StudentRecord {
// Instance variables
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
30
Source Code for StudentRecord
Class
/**
* Returns the name of the student (Accessor method)
*/
public String getName(){
return name;
}
/**
* Changes the name of the student (Mutator method)
*/
public void setName( String temp ){
name = temp;
}
31
Source Code for StudentRecord Class
/**
* Computes the average of the english, math and science
* grades (Accessor method)
*/
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
* returns the number of instances of StudentRecords
* (Accessor method)
*/
public static int getStudentCount(){
return studentCount;
32
}
Sample Source Code that uses
StudentRecord Class
public class StudentRecordExample
{
public static void main( String[] args ){
33
Program Output
Anna
Student Count = 0
34
Overloading
Methods
35
Overloading Methods
● Method overloading
– allows a method with the same name but different
parameters, to have different implementations and return
values of different types
– can be used when the same operation has different
implementations.
37
Example
public static void main( String[] args )
{
StudentRecord annaRecord = new StudentRecord();
annaRecord.setName("Anna");
annaRecord.setAddress("Philippines");
annaRecord.setAge(15);
annaRecord.setMathGrade(80);
annaRecord.setEnglishGrade(95.5);
annaRecord.setScienceGrade(100);
//overloaded methods
annaRecord.print( annaRecord.getName() );
annaRecord.print( annaRecord.getEnglishGrade(),
annaRecord.getMathGrade(),
annaRecord.getScienceGrade());
}
38
Output
● we will have the output for the first call to print,
Name:Anna
Address:Philippines
Age:15
41
Constructors
● To declare a constructor, we write,
<modifier> <className> (<parameter>*) {
<statement>*
}
42
Default Constructor (Method)
● The default constructor (no-arg constructor)
– is the constructor without any parameters.
– If the class does not specify any constructors, then an
implicit default constructor is created.
43
Example: Default Constructor
Method of StudentRecord Class
public StudentRecord()
{
//some code here
}
44
Overloading Constructor Methods
public StudentRecord(){
//some initialization code here
}
public StudentRecord(String temp){
this.name = temp;
}
public StudentRecord(String name, String address){
this.name = name;
this.address = address;
}
public StudentRecord(double mGrade, double eGrade,
double sGrade){
mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
} 45
Using Constructors
● To use these constructors, we have the following code,
46
“this()” constructor call
● Constructor calls can be chained, meaning, you can
call another constructor from inside another
constructor.
● We use the this() call for this
● There are a few things to remember when using the
this() constructor call:
– When using the this constructor call, IT MUST OCCUR AS THE
FIRST STATEMENT in a constructor
– It can ONLY BE USED IN A CONSTRUCTOR DEFINITION. The
this call can then be followed by any other relevant statements.
47
Example
1: public StudentRecord(){
2: this("some string");
3:
4: }
5:
6: public StudentRecord(String temp){
7: this.name = temp;
8: }
9:
10: public static void main( String[] args )
11: {
12:
13: StudentRecord annaRecord = new StudentRecord();
14: }
48
“this” Reference
49
“this” reference
● The this reference
– refers to current object instance itself
● You can only use the this reference for instance variables
and NOT static or class variables.
50
“this” reference
● The this reference is assumed when you call a method
from the same object
52
Access Modifiers
53
Access Modifiers
● There are four different types of member access
modifiers in Java:
– public (Least restrictive)
– protected
– default
54
public accessibility
● public access
– specifies that class members (variables or methods) are
accessible to anyone, both inside and outside the class
and outside of the package.
– Any object that interacts with the class can have access
to the public members of the class.
– Keyword: public
55
Example: “public” Access Modifer
public class StudentRecord {
//default access to instance variable
public int name;
56
protected accessibility
● protected access
– Specifies that the class members are accessible only to
methods in that class and the subclasses of the class.
– The subclass can be in different packages
– Keyword: protected
57
Example: “protected” Access Modifier
public class StudentRecord {
//default access to instance variable
protected String name;
58
default accessibility
● Default access
– specifies that only classes in the same package can have
access to the class' variables and methods
– no actual keyword for the default modifier; it is applied in
the absence of an access modifier.
59
Example
public class StudentRecord {
//default access to instance variable
int name;
60
private accessibility
● private accessibility
– specifies that the class members are only accessible by
the class they are defined in.
– Keyword: private
61
Example: “private” Access Modifier
public class StudentRecord {
//default access to instance variable
private int name;
62
Java Program Structure:
The Access Modifiers
63
Coding Guidelines
● The instance variables of a class should normally be
declared private, and the class will just provide
accessor and mutator methods to these variables.
64
Summary
● Defining your own classes
● Declaring Fields (instance, static/class)
● Declaring Methods (accessor, mutator, static)
● Returning values and Multiple return statements
● The this reference
● Overloading Methods
● Constructors (default, overloading, this() call)
● Packages
● Access Modifiers (default, public, private, protected)
65