8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
1/69
Creating Your OwnClasses
Java Fundamentals and Object-OrientedProgramming
MELJUN CORTES MBA MPA BSCS
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
2/69
Objectives
At the end of the lesson, the student should beable to:
Create their own classesDeclare attributes and methods for their classesUse the this reference to access instance dataCreate and call overloaded methodsImport and create packagesUse access modifiers to control access to classmembers
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
3/69
Defining your own classes
Things to take note of for the syntaxdefined in this section:* means that there may be 0 or more
occurrences of the line where it was applied to. indicates that you have to
substitute an actual value for this part instead
of typing it as it is.[ ] indicates that this part is optional
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
4/69
Defining your own classes
To define a class, we write:
class {
***
}where
is an access modifier, which may becombined with other types of modifier.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
5/69
Example
public class StudentRecord {//we'll add more code here later
}
where,public - means that our class is accessible to otherclasses outside the packageclass - this is the keyword used to create a class inJavaStudentRecord - a unique identifier that describesour class
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
6/69
Best Practice
Think of an appropriate name for yourclass. Don't just call your class XYZ or anyrandom names you can think of.
Class names should start with a CAPITALletter.
The filename of your class should have theSAME NAME as your class name.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
7/69
Declaring Attributes
To declare a certain attribute for our class,we write,
[=];
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
8/69
Instance Variables
public class StudentRecord { 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 withinthe class. Other objects cannot access these variables directly.We will cover more about accessibility later.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
9/69
Best Practice
Declare all your instance variables on the topof the class declaration.Declare one variable for each line.
Instance variables, like any other variablesshould start with a SMALL letter.Use an appropriate data type for each variableyou declare.Declare instance variables as private so thatonly that classs methods can access themdirectly.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
10/69
Class (static) variables
public class StudentRecord {//instance variables we have declaredprivate static int studentCount;//we'll add more code here later
}
w e use the keyw ord s ta t ic to indic a te tha t a
var iable is a s t a t ic var iableRarely a goo d idea, us ual ly acceptable only fo rcons tan t s .
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
11/69
Declaring Methods
To declare methods we write,
([final] *) {*}
where, can carry a number of different modifiers can be any data type (including void) can be any valid identifier ::= [,]
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
12/69
Accessor Methods
Accessor methodsused to read values from our class variables(instance/static).usually written as:
get
It also returns a value.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
13/69
Example 1
public class StudentRecord {
private String name;:
public String getName(){return name;
}}
where,public - means that the method can be called from objects outside
the classString - is the return type of the method. This means that themethod should return a value of type StringgetName - the name of the method() - this means that our method does not have any parameters
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
14/69
Example 2
public class StudentRecord {
private String name;:
public double getAverage(){double result = 0;result=(mathGrade+englishGrade+scienceGra
de)/3;
return result;}
}
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
15/69
Mutator Methods
Mutator Methodsused to write or change values of ourinstance/class variables.Usually written as:
set
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
16/69
Example
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 classvoid - means that the method does not return any valuesetName - the name of the method(String temp) - parameter that will be used inside our method
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
17/69
Multiple return statements
You can have multiple return statementsfor a method as long as they are not on thesame block.
You can also use constants to returnvalues instead of variables.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
18/69
Example
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 variablereturn defaultNum;
}
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
19/69
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 outsidethe classstatic-means that the method is static and should be called bytyping,[ClassName].[methodName]. For example, in this case, wecall the method StudentRecord.getStudentCount()int- is the return type of the method. This means that the methodshould return a value of type intgetStudentCount- the name of the method ()- this means that our method does not have any parameters
i fi l i h h d
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
20/69
Using final with MethodParameters
The values of method parameter usuallydo not change during the execution of amethod.
Declare these parameters final if they donot need to change:
void someMethod( final int x) {
// some code here}
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
21/69
Best Practice
Method names should start with a SMALLletter.Method names should be verbs
Always provide documentation before thedeclaration of the method. You can use
javadoc style for this.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
22/69
Best Practice
Avoid using statics. Static variables aresusceptible to corruption and static methodsmake your design inflexible. Constants are
generally the only acceptable use of statics.Method parameters should usually bedeclared final.
S C d f l
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
23/69
Source Code for classStudentRecord
public class StudentRecord {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;
Source Code for class
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
24/69
Source Code for classStudentRecord
/*** Returns the name of the student*/
public String getName(){return name;
}
/*** Changes the name of the student*/
public void setName( String temp ){name = temp;
}
S C d f l
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
25/69
/*** Computes the average of the english, math and science* grades*/
public double getAverage(){double result = 0;result = ( mathGrade + englishGrade
+ scienceGrade ) / 3;return result;
}/**
* returns the number of instances of StudentRecords*/
public static int getStudentCount(){return studentCount;
}
Source Code for classStudentRecord
Sample Source Code that
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
26/69
Sample Source Code thatuses StudentRecordpublic class StudentRecordExample {
public static void main( String[] args ){
//create three objects for Student recordStudentRecord annaRecord = new StudentRecord();StudentRecord beahRecord = new StudentRecord();StudentRecord crisRecord = new StudentRecord();
//set the name of the studentsannaRecord.setName("Anna");beahRecord.setName("Beah");crisRecord.setName("Cris");
//print anna's nameSystem.out.println( annaRecord.getName() );
//print number of studentsSystem.out.println("Count=
+ StudentRecord.getStudentCount());}
}
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
27/69
Program Output
AnnaStudent Count = 0
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
28/69
this reference
The this referenceReference of an instance to itself.Used by an instance to access its own members
Usually used when an instance variable and a parametervariable have the same name.
To use the this reference, we type,this.
NOTE: You can only use the this reference for instancevariables and NOT class (static) variables.
l P {
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
29/69
class Person {private String lastName;private String firstName;Person(String lastName, String firstName) {
this.lastName = lastName;this.firstName = firstName;
}String getFirstName() {
return firstName;
}void setFirstName(String firstName) {this.firstName = firstName;
}String getLastName() {
return lastName;}
void setLastName(String lastName) {this.lastName = lastName;
}}
l d h d
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
30/69
Overloading Methods
Method overloadingallows a method with the same name but differentparameters, to have different implementations andreturn values of different types
can be used when the same operation has differentimplementations.
Always remember that overloaded methods havethe following properties:
the same namedifferent parametersreturn types can be different or the same
l
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
31/69
Example
public void print String temp ) {System.out.println("Name:" + name);System.out.println("Address:" + address);System.out.println("Age:" + age);
}
public void print double eGrade,double mGrade, double sGrade) {
System.out.println("Name:" + name);System.out.println("Math Grade:" + mGrade);System.out.println("English Grade:" + eGrade);System.out.println("Science Grade:" + sGrade);
}
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
32/69
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 methodsannaRecord.print( annaRecord.getName() );annaRecord.print( annaRecord.getEnglishGrade(),annaRecord.getMathGrade(),annaRecord.getScienceGrade());
}
O
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
33/69
Output
we will have the output for the first call to print,Name:AnnaAddress:PhilippinesAge:15
we will have the output for the second call toprint,Name:Anna
Math Grade:80.0English Grade:95.5Science Grade:100.0
C
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
34/69
Constructors
Constructors are important in instantiating an object.It is a method where initializations are placed.
The following are the properties of a constructor:Constructors have the same name as the classLike methods, constructors can have accessibilitymodifiers and parameters.Unlike methods, constructors do not have any returntype
A constructor may be called only by using the n ew operator during class instantiation.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
35/69
Constructors
To declare a constructor, we write,
(*) {*
}
C
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
36/69
Constructors
This is a constructor:public class Person {
public Person() {}
}This is not a constructor:
public class Person {public void Person() {}
}
D f l C
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
37/69
Default Constructor
The default constructor
is the constructor without any
parameters.If the class does not specify anyconstructors, then an implicit defaultconstructor is created.
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
38/69
Example
If you write a class without a constructor:public StudentRecord(){
//some code here}
The compiler will add the default constructor beforecompiling your code:public StudentRecord(){
public StudentRecord() {super();
}//some code here
}
Overloading Constructors
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
39/69
Overloading Constructors
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;
}
U i C t t
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
40/69
Using Constructors
public static void main( String[] args ){
//create three objects for Studentrecord
StudentRecord annaRecord=newStudentRecord("Anna");
StudentRecord beahRecord=newStudentRecord("Beah",
"Philippines");
StudentRecord crisRecord=newStudentRecord(80,90,100);
//some code here}
this() constructor call
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
41/69
this() constructor call
Constructor calls can be chained, meaning, youcan call another constructor from inside anotherconstructor.We use the this() call for this
There are a few things to remember when usingthe this constructor call:
When using the this constructor call, IT MUSTOCCUR AS THE FIRST STATEMENT in aconstructorIt can ONLY BE USED IN A CONSTRUCTORDEFINITION. The this call can then be followed byany other relevant statements.
E l
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
42/69
Example
public StudentRecord(){
this(""); // default value}
public StudentRecord(String name){
this.name = name;
}
Packages
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
43/69
Packages
Packages have two purposes:Extra layer of encapsulation.Preventing name collision.
k
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
44/69
Packages
Extra layer of encapsulation.You can hide methods, attributes or entireclasses from objects outside the package
provides programmer freedom to implementinternal interactions between classes within apackage without affecting other classes.protects sensitive methods or attributes.
Packages
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
45/69
Packages
Preventing name collision.Two classes can have the same name for aslong as they are in different packages.
I ti P k
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
46/69
Importing Packages
To be able to use classes outside of the packageyou are currently working in, you need to importthe package of those classes.By default, all your Java programs import the
java.lang.* package, that is why you can useclasses like String and Integers inside theprogram eventhough you haven't imported anypackages.The syntax for importing packages is as follows:
import < nameOfPackage> ;
Example
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
47/69
Example
import java.awt.Color;import java.awt.*;
Creating Your Own
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
48/69
Packages
Package declaration should be first non-comment line of code:
package com.calenmartin;
import java.util.*;import java.math.*;
class Foo {
}
Creating Your Own
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
49/69
Packages
Class files must be stored in folder structuredenoted by package name:
com
calenmartin
Foo.class
Creating Your Own
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
50/69
Packages
Package names are usually reverse ofURLs, since URLs are unique:
package org.apache.*;package org.w3c.*:package com.oracle.*;Package com.orangeandbronze.*;
Setting the CLASSPATH
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
51/69
Sett g t e C SS
Now, suppose we place the packageschoolClasses under the C:\ directory.We need to set the classpath to point to that
directory so that when we try to run it, theJVM will be able to see where our classesare stored.Before we discuss how to set the classpath,let us take a look at an example on what willhappen if we don't set the classpath.
Setting the CLASSPATH
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
52/69
Setting the CLASSPATH
Suppose we compile and then run theStudentRecord class we wrote in the last section,
C:\schoolClasses>javac StudentRecord.java
C:\schoolClasses>java StudentRecordException in thread "main" java.lang.NoClassDefFoundError: StudentRecord(wrong name: schoolClasses/StudentRecord)
at java.lang.ClassLoader.defineClass1(Native Method)at java.lang.ClassLoader.defineClass(Unknown Source)at java.security.SecureClassLoader.defineClass(Unknown Source)at java.net.URLClassLoader.defineClass(Unknown Source)at java.net.URLClassLoader.access$100(Unknown Source)at java.net.URLClassLoader$1.run(Unknown Source)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(Unknown Source)at java.lang.ClassLoader.loadClass(Unknown Source)at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)at java.lang.ClassLoader.loadClass(Unknown Source)at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Setting the CLASSPATH
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
53/69
Setting the CLASSPATH
To set the classpath in Windows, we typethis at the command prompt,C:\schoolClasses> set CLASSPATH=C:\
where C:\ is the directory in which we haveplaced the packages
After setting the classpath, we can now
run our program anywhere by typing,C:\schoolClasses> java
schoolClasses.StudentRecord
Setting the CLASSPATH
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
54/69
Setting the CLASSPATH
For Unix base systems, suppose we haveour classes in the directory
/usr/local/myClasses, we write,
exportCLASSPATH=/usr/local/myClasses
Setting the CLASSPATH
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
55/69
g
Take note that you can set the classpathanywhere. You can also set more than oneclasspath, we just have to separate them by ;(forwindows) and : (for Unix based systems). Forexample,
set CLASSPATH=C:\myClasses;D:\;E:\MyPrograms\Java
and for Unix based systems,export CLASSPATH=/usr/local/java:/usr/myClasses
Setting the CLASSPATH
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
56/69
Setting the CLASSPATH
The classpath can also be passed as anoption before calling java or javac
javac classpath C:\myClasses MyClass.javajava classpath C:\myClasses MyClass
or javac cp C:\myClasses MyClass.javajava cp C:\myClasses MyClass
Working with External
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
57/69
Libraries
External libraries are usually distributed injar files. Jar files are basically just zipfiles with a .jar extension.
To use the external libraries, just makesure the jar files are in the CLASSPATH.
set CLASSPATH=C:\MyLibraries\commons-collections.jar;C:\MyLibraries\HttpClient.jar
Access Modifiers
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
58/69
There are four access levels:public - accessible to any objectprotected - only w/in package and subclassesdefault - only w/in packageor friendly private - only w/in class
Access Modifiers
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
59/69
Access Modifiers
For public , protected and private access modifiers are explicitly written inthe code to indicate the access type
For default or friendly access, nokeyword is used.
default accessibility
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
60/69
y
Default accessspecifies that only classes in the samepackage can have access to the class'
variables and methodsno actual keyword for the default modifier; it isapplied in the absence of an access modifier.
Example
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
61/69
p
public class StudentRecord {//default access to instance
variableint name;
//default access to methodString getName(){
return name;}
}
public accessibility
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
62/69
p y
public accessspecifies that class members are accessible toanyone, both inside and outside the class.
Any object that interacts with the class canhave access to the public members of theclass.Keyword: public
Example
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
63/69
p
public class StudentRecord {//default access to instance
variablepublic int name;
//default access to methodpublic String getName(){
return name;}
}
protected accessibility
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
64/69
protected accessspecifies that the class members areaccessible only to methods in that class and
the subclasses of the class.Keyword: protected
Example
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
65/69
public class StudentRecord {//default access to instancevariable
protected int name;
//default access to methodprotected String getName(){
return name;
}}
private accessibility
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
66/69
private accessibilityspecifies that the class members are onlyaccessible by the class they are defined in.Keyword: private
Example
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
67/69
public class StudentRecord {//default access to instancevariable
private int name;
//default access to methodprivate String getName(){
return name;}
}
Best Practice
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
68/69
The instance variables of a class shouldnormally be declared private, and the classwill just provide accessor and mutator
methods to these variables.
Summary
8/10/2019 MELJUN CORTES JAVA_CreatingYourOwnClasses
69/69
Defining your own classesDeclaring Fields (instance, static/class)Declaring Methods (accessor, mutator, static)Returning values and Multiple return statements
The this referenceOverloading MethodsConstructors (default, overloading, this() call)Packages
Classpath and using external libraries Access Modifiers (default, public, private,protected)