0% found this document useful (0 votes)
49 views

FUN 04C CreatingYourOwnClasses

The document discusses how to create and define classes in Java. It explains how to declare attributes, methods, access modifiers, static variables and methods. It provides examples of creating getter and setter methods, multiple return statements, and best practices for naming conventions.

Uploaded by

Emmanuel Royo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

FUN 04C CreatingYourOwnClasses

The document discusses how to create and define classes in Java. It explains how to declare attributes, methods, access modifiers, static variables and methods. It provides examples of creating getter and setter methods, multiple return statements, and best practices for naming conventions.

Uploaded by

Emmanuel Royo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Creating Your Own

Classes

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Objectives
At the end of the lesson, the student should be
able to:
 Create their own classes
 Declare attributes and methods for their classes
 Use the this reference to access instance data
 Create and call overloaded methods
 Import and create packages
 Use access modifiers to control access to class
members

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Defining your own classes
 Things to take note of regarding the syntax
defined in this section:
* means that there may be 0 or more
occurrences of the line where it was applied to.
<description> 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

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Defining your own classes
 To define a class, we write:

[modifier] class <name> {


<attributeDeclaration>*
<constructorDeclaration>*
<methodDeclaration>*
}
 where
 <modifier> is an access modifier, which may be
combined with other types of modifier.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Best Practice
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 should start with a CAPITAL


letter.

The filename of your class should have the


SAME NAME as your class name.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Declaring Attributes
 To declare an attribute for our class we
write,

<modifier> <type> <name> [=


<default_value>];

 Kinds of attribute
 Instance variables
 Static variables / Class variables

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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 within
the class. Other objects cannot access these variables directly.
We will cover more about accessibility later.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Best Practice
Declare all your instance variables on the top of the
class declaration.
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
that class’s methods can access them directly.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Class (static) variables
public class StudentRecord {
//instance variables we have declared
private static int studentCount;
//we'll add more code here later
}

 we use the keyword static to indicate that a


variable is a static variable
 Rarely a good idea, usually acceptable only for
constants.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Declaring Methods
 To declare methods we write,

<modifier> <returnType> <name>


([final] <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>[,]

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Accessor Methods
 Accessor methods
 used to read values from our class variables
(instance/static).
 usually written as:
get<NameOfInstanceVariable>
 It also returns a value.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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 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
 () - this means that our method does not have any parameters

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example 2
public class StudentRecord {
private double mathGrade;
private double englishGrade;
private double scienceGrade;
:
public double getAverage(){
double result = 0;
result=(mathGrade+englishGrade
+scienceGrade)/3;
return result;
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Mutator Methods
 Mutator Methods
 used to write or change values of our instance/
class variables.
 Usually written as:

set<NameOfInstanceVariable>

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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 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

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Multiple return statements
 You can have multiple return statements
for a method as long as they are not in the
same block.
 You can also return constants and
expressions instead of variables.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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 variable
return defaultNum;
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Using “final” with Method
Parameters
 The values of method parameter usually do not
change during the execution of a method.
 Declare these parameters final if they do not need to
change:

void someMethod(final int x) {


// some code here
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Best Practice
 Method names should start with a SMALL letter.
 Method names should be verbs/predicates (more precisely
and preferably, verbs with direct objects). Think along
these lines:
 computeInterestAccrued()
 getAccountBalance()
 initializePlayingField()
 Always provide documentation before the declaration of
the method. You can use javadoc style for this.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Best Practice
 Avoid using statics. Static variables are
susceptible to corruption (several objects
have access to the same variable) and static
methods make your design inflexible.
Constants are generally the only acceptable
use of statics.
 Method parameters should usually be
declared final.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Source Code for class
StudentRecord
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;

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Source Code for class
StudentRecord
/**
* Returns the name of the student
*/
public String getName(){
return name;
}

/**
* Changes the name of the student
*/
public void setName( String temp ){
name = temp;
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Source Code for class
StudentRecord
/**
* 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;
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Sample Source Code that
uses StudentRecord
public class StudentRecordExample {
public static void main( String[] args ){
//create three objects for Student record
StudentRecord annaRecord = new StudentRecord();
StudentRecord beahRecord = new StudentRecord();
StudentRecord crisRecord = new StudentRecord();
//set the name of the students
annaRecord.setName("Anna");
beahRecord.setName("Beah");
crisRecord.setName("Cris");
//print anna's name
System.out.println( annaRecord.getName() );
//print number of students
System.out.println("Count=”
+ StudentRecord.getStudentCount());
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Program Output
Anna
Student Count = 0

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
“this” reference
 The this reference
 Reference of an instance to itself.
 Used by an instance to access its own members
 Generally used when an instance variable and a parameter
variable have the same name.
 To use the this reference, we type,
this.<nameOfTheInstanceVariable>

 NOTE: You can only use the this reference for instance
variables and NOT class (static) variables.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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;
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Overloading Methods
 Method overloading
 allows a method with the same name but different
parameters, to have different implementations and
return values of different types.
 Always remember that overloaded methods have
the following properties:
 the same name
 different parameters
 return types can be different or the same

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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);
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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());
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Output
 we will have the output for the first call to print,
Name:Anna
Address:Philippines
Age:15

 we will have the output for the second call to


print,
Name:Anna
Math Grade:80.0
English Grade:95.5
Science Grade:100.0

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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 class
 Like methods, constructors can have accessibility
modifiers and parameters.
 Unlike methods, constructors do not have any return
type
 A constructor may be called only by using the new
operator during class instantiation.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Constructors
 To declare a constructor, we write,

<accessModifier> <className> (<parameter>*) {


<statement>*
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Constructors
 This is a constructor:
public class Person {
public Person() {
}
}
 This is not a constructor:
public class Person {
public void Person() {
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Default Constructor
 The default constructor
 is the constructor without any
parameters.
 If the class does not specify any
constructors, then an implicit default
constructor is created.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
 If you write a class without a constructor:
public StudentRecord(){
//some code here
}

 The compiler will add the default constructor before


compiling your code:
public StudentRecord(){
public StudentRecord() {
super();
}
//some code here
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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;
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Using Constructors

public static void main( String[] args ){


//create three objects for Student record
StudentRecord annaRecord=
new StudentRecord("Anna");

StudentRecord beahRecord=
new StudentRecord("Beah","Philippines");

StudentRecord crisRecord=
new StudentRecord(80,90,100);
//some code here
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
“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.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
public StudentRecord(){
this(""); // default value
}

public StudentRecord(String name){


this.name = name;
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Packages
 Packages have two purposes:
 Extra layer of encapsulation.
 Preventing name collision.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Packages
 Extra layer of encapsulation.
 You can hide methods, attributes or entire
classes from objects outside the package…
 …provides programmer freedom to implement
internal interactions between classes within a
package without affecting other classes.
 …protects sensitive methods or attributes.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Packages
 Preventing name collision.
 Two classes can have the same name for as
long as they are in different packages.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Importing Packages
 To be able to use classes outside of the package
you are currently working in, you need to import
the package of those classes.
 By default, all your Java programs import the
java.lang.* package, that is why you can use
classes like String and Integers inside the
program eventhough you haven't imported any
packages.
 The syntax for importing packages is as follows:
import <nameOfPackage>;

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
import java.awt.Color;
import java.awt.*;

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Creating Your Own
Packages
 Package declaration should be first non-
comment line of code:

package com.calenmartin;

import java.util.*;
import java.math.*;

class Foo {

}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Creating Your Own
Packages
 Class files must be stored in folder structure
denoted by package name:

com

calenmartin

Foo.class

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Creating Your Own
Packages
 Package names are usually reverse of
URLs, since URLs are unique:

package org.apache.*;
package org.w3c.*:
package com.oracle.*;
Package com.orangeandbronze.*;

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Setting the CLASSPATH
 Now, suppose we place the package
schoolClasses under the C:\ directory.
 We need to set the classpath to point to that
directory so that when we try to run it, the
JVM will be able to see where our classes are
stored.
 Before we discuss how to set the classpath,
let us take a look at an example on what will
happen if we don't set the classpath.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Setting the CLASSPATH
 Suppose we compile and then run the
StudentRecord class we wrote in the last
section,

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Setting the CLASSPATH
 To set the classpath in Windows, we type
this at the command prompt,
C:\schoolClasses> set CLASSPATH=C:\
 where C:\ is the directory in which we have
placed the packages
 After setting the classpath, we can now
run our program anywhere by typing,
C:\schoolClasses> java
schoolClasses.StudentRecord

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Setting the CLASSPATH
 For Unix base systems, suppose we have
our classes in the directory
/usr/local/myClasses, we write,

export
CLASSPATH=/usr/local/myClasses

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Setting the CLASSPATH
 Take note that you can set the classpath
anywhere. You can also set more than one
classpath, we just have to separate them by ;(for
windows) and : (for Unix based systems). For
example,
set CLASSPATH=C:\myClasses;D:\;E:\MyPrograms\Java

 and for Unix based systems,


export CLASSPATH=/usr/local/java:/usr/myClasses

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Setting the CLASSPATH
 The classpath can also be passed as an
option before calling java or javac

javac –classpath C:\myClasses


MyClass.java
java –classpath C:\myClasses MyClass
or
javac –cp C:\myClasses MyClass.java
java –cp C:\myClasses MyClass

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Working with External
Libraries
 External libraries are usually distributed in
“jar” files. Jar files are basically just zip
files with a “.jar” extension.
 To use the external libraries, just make
sure the jar files are in the CLASSPATH.
set CLASSPATH=C:\MyLibraries\commons-collecti
ons.jar;C:\MyLibraries\HttpClient.jar

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Access Modifiers
 There are four access levels:
 public - accessible to any object
 protected - only within package and
subclasses
 default - only within package
or “friendly”
 private - only within class

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Access Modifiers
 public, protected and private access
modifiers are explicitly written in the code
to indicate the access type
 For default or “friendly” access, no
keyword is used.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
public class StudentRecord {
//default access to instance variable
int name;

//default access to method


String getName(){
return name;
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
public accessibility
 public access
 specifies that class members are accessible
everywhere, both inside and outside the class.
 Any object that interacts with the class can
have access to the public members of the
class.
 Keyword: public

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
public class StudentRecord {
//public access to instance variable
public int name;

//public access to method


public String getName(){
return name;
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
protected accessibility
 protected access
 specifies that the class members are
accessible only to methods in that class and
the subclasses of the class.
 Keyword: protected

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
public class StudentRecord {
//protected access to instance variable
protected int name;

//protected access to method


protected String getName(){
return name;
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
private accessibility
 private accessibility
 specifies that the class members can only be
accessed by the class they are defined in.
 Keyword: private

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Example
public class StudentRecord {
//private access to instance variable
private int name;

//private access to method


private String getName(){
return name;
}
}

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
Best Practice
 The instance variables of a class should
normally be declared private, and the class
will just provide accessor and mutator
methods to these variables.

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved
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
 Classpath and using external libraries
 Access Modifiers (default, public, private,
protected)

Copyright 2008 Orange & Bronze Software Labs Ltd.Co. All Rights Reserved

You might also like