Sie sind auf Seite 1von 54

Introduction to Programming 1 1

10 Creating your own


Classes
Introduction to Programming 1 2
Topics

Defining your own classes

Declaring Fields

Instance Variables

Class Variables or Static Variables

Declaring Methods

Multiple return statements

The this reference

Overloading Methods

Declaring Constructors

The this! Constructor Call


Introduction to Programming 1 3
Topics

"ac#ages

Importing "ac#ages

Creating your own pac#ages

$ccess Modifiers default% public% private% protected!


Introduction to Programming 1 4
Defining your own classes

Sample Class to create&

contains information of a Student and operations needed for a


certain student record

To create class&
'( Thin# on where you will be using your class and how
your class will be used(
)( Thin# of an appropriate name for the class
*( +ist all the information or properties that you want your
class to contain
,( +ist down the methods that you will be using for your
class(
Introduction to Programming 1 5
Defining your own classes

-ow% to define our class we write%


where%
public . means that our class is accessible to other classes outside the
pac#age
class . this is the #eyword used to create a class in /ava
Student0ecord . a uni1ue identifier that describes our class
public class StudentRecord {
//we'll add more code here later
}
Introduction to Programming 1 6
Defining your own classes:
Coding Guidelines
'( Thin# of an appropriate name for your class( Don2t 3ust call
your class 456 or any random names you can thin# of(
)( Class names should start with a C$"IT$+ letter(
*( The filename of your class should have the S$M7 -$M7 as
your class name(
Introduction to Programming 1 7
Declaring Fields

+et us now write down a list of information that a student


record can contain( For each information% also list what data
types would be appropriate to use(
name . String
address . String
age . int
math grade . double
english grade . double
science grade . double
average grade . double
Introduction to Programming 1 8
Declaring Fields:
Instance Variables

-ow that we have a list of all the properties we want to add


to our class% let us now add them to our code(
where%
private . means that the variables are only accessible
within the class( Other ob3ects cannot access
these variables directly( 8e will cover more
about accessibility later(
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
}
Introduction to Programming 1 9
Declaring Fields:
Coding Guidelines
'( Declare all your instance variables on the top of the class
declaration(
)( Declare one variable for each line(
*( Instance variables% li#e any other variables should start with
a SM$++ letter(
,( 9se an appropriate data type for each variable you declare(
:( Declare instance variables as private so that only class
methods can access them directly(
Introduction to Programming 1 10
Declaring Fields:
Static Variables

$side from instance variables% we can also declare class


variables or variables that belong to the class as a whole(

The value of these variables are the same for all the ob3ects
of the same class(

To declare a static variable%


public class StudentRecord {
//instance variables we have declared
private static int studentCount;
//we'll add more code here later
}
we use the #eyword static to indicate that a variable is a
static variable(
Introduction to Programming 1 11
Declaring Fields

So far% our whole code now loo#s li#e this(


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;
//we'll add more code here later
}
Introduction to Programming 1 12
Declaring Metods

+et2s now list down the set of functionalities that we want our
class to have(

8e want to access information about the student li#e what


the student2s name is% what2s his;her address and other
information(

<owever% we declared these variables to be private% so they


are only accessible within the class(
Introduction to Programming 1 13
Declaring Metods:
!ccessor " Mutator Metods

$ccessor Methods

Methods used to read values from our class variables(

Mutator Methods

Methods used to write or change values of our class variables(

-OT7& 5ou can restrict access to a class variable by not


creating an accessor method for it(
Introduction to Programming 1 14
Declaring Metods:
!ccessor " Mutator Metods

To summari=e% we have the list of accessor and mutator


methods and what it can do%
name . read
write address . read% write
english grade . read% write
math grade . read% write
science grade . read% write
average grade . compute;read
studentCount . read
Introduction to Programming 1 15
Declaring Metods:
!ccessor " Mutator Metods

$n accessor method usually starts with a


get>-ameOfInstanceVariable?

$ mutator method usually starts with a


set>-ameOfInstanceVariable?
Introduction to Programming 1 16
Declaring Metods:
!ccessor " Mutator Metods

So% given the previous list% we can have the following names
for our accessor and mutator methods%
name . get-ame% set-ame
write address . get$ddress% set$ddress
english grade . get7nglish@rade% set7nglish@rade
math grade . getMath@rade% setMath@rade
science grade . getScience@rade% setScience@rade
average grade . get$verage@rade
studentCount . getStudentCount
Introduction to Programming 1 17
Declaring Metods:
!ccessor " Mutator Metods

One sample implementation of a get! method%


where%
public . means that the method can be called from ob3ects outside the class
String . is the return type of the method( This means that the method should
return a value of type String
get-ame . the name of the method
! . this means that our method does not have any parameters
public class StudentRecord {
private String name;
:
:
public String getName(){
return name;
}
}
Introduction to Programming 1 18
Declaring Metods:
!ccessor " Mutator Metods

The statement%
return name;
in our program signifies that it will return the value of the
instance variable name to the calling method(

-OT7& The return type of the method should have the same
data type as the data in the return statement(
Introduction to Programming 1 19
Declaring Metods:
Multiple return state#ents

5ou can have multiple return statements for a method as


long as they are not on the same bloc#(

5ou can also use constants to return values instead of


variables(
Introduction to Programming 1 20
Declaring Metods:
Multiple return state#ents

7Aample&
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;
}
Introduction to Programming 1 21
Declaring Metods:
!ccessor Metods

One sample implementation of a set! method%


where%
public . means that the method can be called from ob3ects outside the class
void . means that the method does not return any value
set-ame . the name of the method
String temp! . parameter that will be used inside our method
public class StudentRecord {
private String name;
:
:
public void setName( String temp ){
name = temp;
}
}
Introduction to Programming 1 22
Declaring Metods:
!ccessor Metods

The statement%
name = temp;
assigns the value of temp to name and thus changes the
data inside the instance variable name(

-OT7& Set methods don2t return values( <owever% it


contains some program argument or arguments that will be
used inside the method(
Introduction to Programming 1 23
Declaring Metods:
Coding Guidelines
'( Method names should start with a SM$++ letter(
)( Method names should be verbs
*( $lways provide documentation before the declaration of the
method( 5ou can use 3avadocs style for this(
Introduction to Programming 1 24
Declaring Metods:
!ccessor Metods

For the static variable studentCount% we can create a static


method to access its value(

where%
public . means that the method can be called from ob3ects outside the class
static . means that the method is static and should be called by typing%
>Class-ame?(>method-ame?(
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
public class StudentRecord {
:
private static int studentCount;
:
:
public static int getStudentCount(){
return studentCount;
}
}
Introduction to Programming 1 25
Code for Student$ecord
Class
1 public class StudentRecord
2 {
3 private String name;
4 private String address;
5 private int age;
6 private double mathGrade;
7 private double englishGrade;
8 private double scienceGrade;
9 private double average;
10 private static int studentCount;
11
12 /**
13 * Returns the name of the student
14 */
15 public String getName(){
16 return name;
17 }
Introduction to Programming 1 26
Code for Student$ecord
Class
18 /**
19 * Changes the name of the student
20 */
21 public void setName( String temp ){
22 name = temp;
23 }
24
25 // other code here ....
26
27 /**
28 * Computes the average of the english, math and
science
29 * grades
30 */
31 public double getAverage(){
32 double result = 0;
33 result = ( mathGrade+englishGrade+scienceGrade )/3;
34 return result;
35 }
Introduction to Programming 1 27
Code for Student$ecord
class
36 /**
37 * returns the number of instances of StudentRecords
38 */
39 public static int getStudentCount(){
40 return studentCount;
41 }
42 }
Introduction to Programming 1 28
Sa#ple Code of a class tat
uses Student$ecord class
1 public class StudentRecordExample
2 {
3 public static void main( String[] args ){
4 //create three objects for Student record
5 StudentRecord annaRecord = new StudentRecord();
6 StudentRecord beahRecord = new StudentRecord();
7 StudentRecord crisRecord = new StudentRecord();
8
9 //set the name of the students
10 annaRecord.setName("Anna");
11 beahRecord.setName("Beah");
12 crisRecord.setName("Cris");
13
14 //print anna's name
15 System.out.println( annaRecord.getName() );
16 //print number of students
17 System.out.println("Count=" +
18 StudentRecord.getStudentCount ());
19 }
20 }
Introduction to Programming 1 29
Te %tis& reference

The this reference is used to access the instance variables


shadowed by the parameters(

To understand this better% let2s ta#e for eAample the set$ge


method( Suppose we have the following declaration for
set$ge(

The parameter name in this declaration is age% which has


the same name as the instance variable age( Since the
parameter age is the closest declaration to the method% the
value of the parameter age will be used(
public void setAge( int age ){
age = age; //WRONG!!!
}
Introduction to Programming 1 30
Te %tis& reference

In order to correct this mista#e% we use the BthisC reference(

To use the this reference% we type%


this.[nameOfTheInstanceVariable]

So for example, we can now rewrite our code to,


public void setAge( int age ){
this.age = age;
}
Introduction to Programming 1 31
Te %tis& reference

-OT7& 5ou can only use the this reference for instance
variables and -OT static or class variables(
Introduction to Programming 1 32
'(erloading Metods

Method overloading

allows a method with the same name but different parameters% to


have different implementations and return values of different types(

0ather than invent new names all the time% method overloading can
be used when the same operation has different implementations(
Introduction to Programming 1 33
'(erloading Metods:
Sa#ple )rogra#
1 /**
2 * overloaded method print() - one parameter
3 */
4 public void print( String temp )
5 {
6 System.out.println("Name:" + name);
7 System.out.println("Address:" + address);
8 System.out.println("Age:" + age);
9 }
10
11 /**
12 * overloaded method print() - three parameters
13 */
14 public void print(double eGrade,double mGrade,double sGrade)
15 {
16 System.out.println("Name:" + name);
17 System.out.println("Math Grade:" + mGrade);
18 System.out.println("English Grade:" + eGrade);
19 System.out.println("Science Grade:" + sGrade);
20 }
Introduction to Programming 1 34
'(erloading Metods:
Sa#ple )rogra#

-ow calling those methods in main!


1 public static void main( String[] args ) {
2 StudentRecord annaRecord = new StudentRecord();
3 annaRecord.setName("Anna");
4 annaRecord.setAddress("Philippines");
5 annaRecord.setAge(15);
6 annaRecord.setMathGrade(80);
7 annaRecord.setEnglishGrade(95.5);
8 annaRecord.setScienceGrade(100);
9 //overloaded methods
10 annaRecord.print( annaRecord.getName() );
11 annaRecord.print( annaRecord.getEnglishGrade(),
12 annaRecord.getMathGrade(),
13 annaRecord.getScienceGrade());
14 }
Introduction to Programming 1 35
'(erloading Metods:
Sa#ple )rogra# 'utput

For print call in line 'D% the output is%

For print call in line ''% the output is%


Name:Anna
Address:Philippines
Age:15
Name:Anna
Math Grade:80.0
English Grade:95.5
Science Grade:100.0
Introduction to Programming 1 36
'(erloading Metods

$lways remember that overloaded methods have the


following properties&

the same name

different parameters

return types can be different or the same


Introduction to Programming 1 37
Declaring Constructors

Constructors are important in instantiating an ob3ect( It is a


method where all the initiali=ations are placed(

"roperties of a constructor&
'( Constructors have the same name as the class
)( $ constructor is 3ust li#e an ordinary method% however only the
following information can be placed in the header of the constructor%
scope or accessibility identifier li#e public(((!% constructor2s name
and parameters if it has any(
*( Constructors does not have any return value
,( 5ou cannot call a constructor directly% it can only be called by using
the new operator during class instantiation(
Introduction to Programming 1 38
Declaring Constructors:
Te default constructor

7very class has a 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(

7Aample&
public StudentRecord() {
//some code here
}
Introduction to Programming 1 39
Declaring Constructors:
Constructor o(erloading

Since constructors are 3ust li#e methods% they can also be


overloaded(

7Aample&
1 public StudentRecord(){
2 //some initialization code here
3 }
4
5 public StudentRecord(String temp){
6 this.name = temp;
7 }
8
9 public StudentRecord(String name, String address){
10 this.name = name;
11 this.address = address;
12 }
Introduction to Programming 1 40
Declaring Constructors:
Constructor o(erloading

To use these constructors% we have&


1 public static void main( String[] args )
2 {
3 //create three objects for Student record
4 StudentRecord annaRecord=new StudentRecord("Anna");
5 StudentRecord beahRecord=new StudentRecord("Beah",
6 "Philippines");
7 StudentRecord crisRecord=new StudentRecord ();
8 }
Introduction to Programming 1 41
Declaring Constructors:
Te %tis*+& constructor call

Constructor calls can be chained% meaning% you can call


another constructor from inside another constructor(

8e use the this! call for this(

There are a few things to remember when using the this


constructor call&
'( 8hen using the this constructor call% IT M9ST OCC90 $S T<7
FI0ST ST$T7M7-T in a constructor
)( It can O-+5 E7 9S7D I- $ CO-ST09CTO0 D7FI-ITIO-( The this
call can then be followed by any other relevant statements(
Introduction to Programming 1 42
Declaring Constructors:
Te %tis& constructor call
1 public StudentRecord(){
2 this("some string");
3 }
4
5 public StudentRecord(String temp){
6 this.name = temp;
7 }
8
9 public static void main( String[] args ){
10 StudentRecord annaRecord = new StudentRecord();
11 }
Introduction to Programming 1 43
)ac,ages

"ac#ages are /avaFs means of grouping related classes and


interfaces together in a single unit interfaces will be
discussed later!(

This powerful feature provides for a convenient mechanism


for managing a large group of classes and interfaces while
avoiding potential naming conflicts(
Introduction to Programming 1 44
)ac,ages:
I#porting )ac,ages

To be able to use classes outside of the pac#age you are


currently wor#ing in% you need to import the pac#age of
those classes(

Ey default% all your /ava programs import the 3ava(lang(G


pac#age% that is why you can use classes li#e String and
Integers inside the program even though you haven2t
imported any pac#ages(

The syntaA for importing pac#ages is as follows%



import nameOfPackage;
Introduction to Programming 1 45
)ac,ages:
I#porting )ac,ages

7Aample&

The first statement imports the specific class Color while the
other imports all of the classes in the 3ava(awt pac#age(
import java.awt.Color;
import java.awt.*;
Introduction to Programming 1 46
)ac,ages:
Creating your own pac,ages

Suppose we want to create a pac#age where we will place


our Student0ecord class% together with other related
classes( 8e will call our pac#age% SchoolClasses(

Steps&
'( Create a folder named SchoolClasses(
)( Copy all the classes that you want to belong to this pac#age inside
this folder(
*( $dd the following code at the top of the class file(
package SchoolClasses;
public class StudentRecord{
. . . .
Introduction to Programming 1 47
)ac,ages:
Creating your own pac,ages

"ac#ages can also be nested(

In this case% the /ava interpreter eApects the directory


structure containing the eAecutable classes to match the
pac#age hierarchy(
Introduction to Programming 1 48
!ccess Modifiers

8hen creating our classes and defining the properties and


methods in our class% we want to implement some #ind of
restriction to access these data(

In /ava% we have what we call access modifiers in order to


implement this(

Four different types of member access modifiers in /ava&

public

private

protected

default(
Introduction to Programming 1 49
!ccess Modifiers:
default access

default access

$lso called pac#age accessibility

This specifies that only classes in the same pac#age can have
access to the class2 variables and methods(

There are no actual #eyword for the default modifierH it is applied in


the absence of an access modifier(

7Aample&
public class StudentRecord {
//default access to instance variable
int name;
//default access to method
String getName(){
return name;
}
}
Introduction to Programming 1 50
!ccess Modifiers:
public access

This specifies that class members are accessible to anyone%


both inside and outside the class(

$ny ob3ect that interacts with the class can have access to
the public members of the class(

7Aample&
public class StudentRecord {
//public access to instance variable
public int name;
//public access to method
public String getName(){
return name;
}
}
Introduction to Programming 1 51
!ccess Modifiers:
protected access

This specifies that the class members are accessible only to


methods in that class and the subclasses of the class(

7Aample&
public class StudentRecord {
//protected access to instance variable
protected int name;
//protected access to method
protected String getName(){
return name;
}
}
Introduction to Programming 1 52
!ccess Modifiers:
pri(ate access

This specifies that the class members are only accessible by


the class they are defined in(

7Aample&
public class StudentRecord {
//private access to instance variable
private int name;
//private access to method
private String getName(){
return name;
}
}
Introduction to Programming 1 53
!ccess Modifiers:
Coding Guidelines

The instance variables of a class should normally be


declared private% and the class will 3ust provide accessor
methods which are declared as public! to these variables(
Introduction to Programming 1 54
Su##ary

Defining your own classes

Declaring Fields Instance Variables% Class Variables or


Static Variables!

Declaring Methods

0eturning values and Multiple return statements

The this reference

Overloading Methods

Declaring Constructors

The this! Constructor Call

"ac#ages

$ccess Modifiers default% public% private% protected!

Das könnte Ihnen auch gefallen