Creating Your Own Classes Sxi

Embed Size (px)

Citation preview

  • 8/11/2019 Creating Your Own Classes Sxi

    1/54

    Introduction to Programming 1 1

    10 Creating your ownClasses

  • 8/11/2019 Creating Your Own Classes Sxi

    2/54

    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

  • 8/11/2019 Creating Your Own Classes Sxi

    3/54

    Introduction to Programming 1 3

    Topics "ac#ages

    Importing "ac#ages Creating your own pac#ages

    $ccess Modifiers default% public% private% protected!

  • 8/11/2019 Creating Your Own Classes Sxi

    4/54

    Introduction to Programming 1 4

    Defining your own classes Sample Class to create&

    contains information of a Student and operations needed for acertain 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(

  • 8/11/2019 Creating Your Own Classes Sxi

    5/54

    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#ageclass . this is the #eyword used to create a class in /avaStudent0ecord . a uni1ue identifier that describes our class

    public class StudentRecord {

    //we'll add more code here later

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    6/54

    Introduction to Programming 1 6

    Defining your own classes:

    Coding Guidelines'( Thin# of an appropriate name for your class( Don2t 3ust callyour 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 asyour class name(

  • 8/11/2019 Creating Your Own Classes Sxi

    7/54

    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 datatypes would be appropriate to use(

    name . Stringaddress . Stringage . intmath grade . doubleenglish grade . doublescience grade . doubleaverage grade . double

  • 8/11/2019 Creating Your Own Classes Sxi

    8/54

    Introduction to Programming 1 8

    Declaring Fields:Instance Variables

    -ow that we have a list of all the properties we want to addto 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

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    9/54

    Introduction to Programming 1 9

    Declaring Fields:

    Coding Guidelines'( Declare all your instance variables on the top of the classdeclaration(

    )( Declare one variable for each line(

    *( Instance variables% li#e any other variables should start witha 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(

  • 8/11/2019 Creating Your Own Classes Sxi

    10/54

    Introduction to Programming 1 10

    Declaring Fields:

    Static Variables $side from instance variables% we can also declare classvariables 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 declaredprivate static int studentCount;//we'll add more code here later

    }

    we use the #eyword static to indicate that a variable is astatic variable(

  • 8/11/2019 Creating Your Own Classes Sxi

    11/54

    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

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    12/54

    Introduction to Programming 1 12

    Declaring Met ods +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 whatthe student2s name is% what2s his;her address and otherinformation(

  • 8/11/2019 Creating Your Own Classes Sxi

    13/54

    Introduction to Programming 1 13

    Declaring Met ods:

    !ccessor " Mutator Met ods $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(

  • 8/11/2019 Creating Your Own Classes Sxi

    14/54

    Introduction to Programming 1 14

    Declaring Met ods:

    !ccessor " Mutator Met ods To summari=e% we have the list of accessor and mutatormethods and what it can do%

    name . readwrite address . read% writeenglish grade . read% writemath grade . read% writescience grade . read% writeaverage grade . compute;read

    studentCount . read

  • 8/11/2019 Creating Your Own Classes Sxi

    15/54

    Introduction to Programming 1 15

    Declaring Met ods:

    !ccessor " Mutator Met ods $n accessor method usually starts with aget>-ameOfInstanceVariable?

    $ mutator method usually starts with a

    set>-ameOfInstanceVariable?

  • 8/11/2019 Creating Your Own Classes Sxi

    16/54

    Introduction to Programming 1 16

    Declaring Met ods:

    !ccessor " Mutator Met ods So% given the previous list% we can have the following namesfor our accessor and mutator methods%

    name . get-ame% set-amewrite address . get$ddress% set$ddressenglish grade . get7nglish@rade% set7nglish@rademath grade . getMath@rade% setMath@radescience grade . getScience@rade% setScience@radeaverage grade . get$verage@rade

    studentCount . getStudentCount

  • 8/11/2019 Creating Your Own Classes Sxi

    17/54

    Introduction to Programming 1 17

    Declaring Met ods:

    !ccessor " Mutator Met ods One sample implementation of a get ! method%

    where%

    public . means that the method can be called from ob3ects outside the classString . is the return type of the method( This means that the method shouldreturn a value of type Stringget-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;

    }}

  • 8/11/2019 Creating Your Own Classes Sxi

    18/54

    Introduction to Programming 1 18

    Declaring Met ods:

    !ccessor " Mutator Met ods The statement%return name;

    in our program signifies that it will return the value of theinstance variable name to the calling method(

    -OT7& The return type of the method should have the samedata type as the data in the return statement(

  • 8/11/2019 Creating Your Own Classes Sxi

    19/54

    Introduction to Programming 1 19

    Declaring Met ods:

    Multiple return state#ents 5ou can have multiple return statements for a method aslong as they are not on the same bloc#(

    5ou can also use constants to return values instead ofvariables(

  • 8/11/2019 Creating Your Own Classes Sxi

    20/54

    Introduction to Programming 1 20

    Declaring Met ods:

    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 variablereturn defaultNum;

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    21/54

    Introduction to Programming 1 21

    Declaring Met ods:

    !ccessor Met ods One sample implementation of a set ! method%

    where%public . means that the method can be called from ob3ects outside the classvoid . means that the method does not return any valueset-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;}

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    22/54

    Introduction to Programming 1 22

    Declaring Met ods:

    !ccessor Met ods The statement%name = temp;

    assigns the value of temp to name and thus changes thedata inside the instance variable name(

    -OT7& Set methods don2t return values(

  • 8/11/2019 Creating Your Own Classes Sxi

    23/54

    Introduction to Programming 1 23

    Declaring Met ods:

    Coding Guidelines'( Method names should start with a SM$++ letter(

    )( Method names should be verbs

    *( $lways provide documentation before the declaration of themethod( 5ou can use 3avadocs style for this(

    D l i M d

  • 8/11/2019 Creating Your Own Classes Sxi

    24/54

    Introduction to Programming 1 24

    Declaring Met ods:!ccessor Met ods

    For the static variable studentCount% we can create a staticmethod 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 intgetStudentCount .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;}

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    25/54

    Introduction to Programming 1 25

    Code for Student$ecord

    Class1 public class StudentRecord2 {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;1112 /**13 * Returns the name of the student14 */15 public String getName(){16 return name;17 }

  • 8/11/2019 Creating Your Own Classes Sxi

    26/54

    Introduction to Programming 1 26

    Code for Student$ecord

    Class18 /**19 * Changes the name of the student20 */21 public void setName( String temp ){22 name = temp;23 }

    2425 // other code here ....2627 /**28 * Computes the average of the english, math and

    science

    29 * grades30 */31 public double getAverage(){32 double result = 0;33 result = ( mathGrade+englishGrade+scienceGrade )/3;34 return result;

    35 }

  • 8/11/2019 Creating Your Own Classes Sxi

    27/54

    Introduction to Programming 1 27

    Code for Student$ecord

    class36 /**37 * returns the number of instances of StudentRecords38 */39 public static int getStudentCount(){40 return studentCount;41 }42 }

  • 8/11/2019 Creating Your Own Classes Sxi

    28/54

  • 8/11/2019 Creating Your Own Classes Sxi

    29/54

    Introduction to Programming 1 29

    T e %t is& 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$gemethod( Suppose we have the following declaration forset$ge(

    The parameter name in this declaration is age % which hasthe same name as the instance variable age ( Since theparameter age is the closest declaration to the method% thevalue of the parameter age will be used(

    public void setAge( int age ){age = age; //WRONG!!!

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    30/54

    Introduction to Programming 1 30

    T e %t is& reference In order to correct this mista#e% we use the Bthis 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;}

  • 8/11/2019 Creating Your Own Classes Sxi

    31/54

    Introduction to Programming 1 31

    T e %t is& reference -OT7& 5ou can only use the this reference for instance

    variables and -OT static or class variables (

  • 8/11/2019 Creating Your Own Classes Sxi

    32/54

    Introduction to Programming 1 32

    '(erloading Met ods Method overloading

    allows a method with the same name but different parameters% tohave different implementations and return values of different types(

    0ather than invent new names all the time% method overloading canbe used when the same operation has different implementations(

    ( l d d

  • 8/11/2019 Creating Your Own Classes Sxi

    33/54

    Introduction to Programming 1 33

    '(erloading Met ods:Sa#ple )rogra#1 /**

    2 * overloaded method print() - one parameter3 */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 }1011 /**12 * overloaded method print() - three parameters13 */

    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 }

  • 8/11/2019 Creating Your Own Classes Sxi

    34/54

    Introduction to Programming 1 34

    '(erloading Met ods:

    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 methods10 annaRecord.print( annaRecord.getName() );11 annaRecord.print( annaRecord.getEnglishGrade(),12 annaRecord.getMathGrade(),13 annaRecord.getScienceGrade());14 }

  • 8/11/2019 Creating Your Own Classes Sxi

    35/54

    Introduction to Programming 1 35

    '(erloading Met ods:

    Sa#ple )rogra# 'utput For print call in line ' % the output is%

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

    Name:AnnaAddress:PhilippinesAge:15

    Name:AnnaMath Grade:80.0English Grade:95.5Science Grade:100.0

  • 8/11/2019 Creating Your Own Classes Sxi

    36/54

    Introduction to Programming 1 36

    '(erloading Met ods $lways remember that overloaded methods have the

    following properties& the same name different parameters return types can be different or the same

  • 8/11/2019 Creating Your Own Classes Sxi

    37/54

    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 thefollowing information can be placed in the header of the constructor%scope or accessibility identifier li#e public(((!% constructor2s nameand parameters if it has any(

    *( Constructors does not have any return value

    ,( 5ou cannot call a constructor directly % it can only be called by usingthe new operator during class instantiation(

  • 8/11/2019 Creating Your Own Classes Sxi

    38/54

    Introduction to Programming 1 38

    Declaring Constructors:

    T e 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 animplicit default constructor is created(

    7Aample&public StudentRecord() { //some code here

    }

  • 8/11/2019 Creating Your Own Classes Sxi

    39/54

    Introduction to Programming 1 39

    Declaring Constructors:

    Constructor o(erloading Since constructors are 3ust li#e methods% they can also beoverloaded(

    7Aample&1 public StudentRecord(){2 //some initialization code here3 }45 public StudentRecord(String temp){6 this.name = temp;

    7 }89 public StudentRecord(String name, String address){10 this.name = name;11 this.address = address;12 }

  • 8/11/2019 Creating Your Own Classes Sxi

    40/54

    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 record4 StudentRecord annaRecord=new StudentRecord("Anna");5 StudentRecord beahRecord=new StudentRecord("Beah",6 "Philippines");7 StudentRecord crisRecord=new StudentRecord ();8 }

  • 8/11/2019 Creating Your Own Classes Sxi

    41/54

    Introduction to Programming 1 41

    Declaring Constructors:T e %t is*+& constructor call

    Constructor calls can be chained% meaning% you can callanother constructor from inside another constructor(

    8e use the this ! call for this(

    There are a few things to remember when using the thisconstructor call&

    '( 8hen using the this constructor call% IT M9ST OCC90 $S T

  • 8/11/2019 Creating Your Own Classes Sxi

    42/54

    Introduction to Programming 1 42

    Declaring Constructors:T e %t is& constructor call

    1 public StudentRecord(){2 this("some string");3 }45 public StudentRecord(String temp){6 this.name = temp;7 }89 public static void main( String[] args ){10 StudentRecord annaRecord = new StudentRecord();11 }

  • 8/11/2019 Creating Your Own Classes Sxi

    43/54

    Introduction to Programming 1 43

    )ac,ages "ac#ages are /ava s means of grouping related classes and

    interfaces together in a single unit interfaces will bediscussed later!(

    This powerful feature provides for a convenient mechanismfor managing a large group of classes and interfaces whileavoiding potential naming conflicts(

    )

  • 8/11/2019 Creating Your Own Classes Sxi

    44/54

    Introduction to Programming 1 44

    )ac,ages:I#porting )ac,ages

    To be able to use classes outside of the pac#age you arecurrently wor#ing in% you need to import the pac#age ofthose classes(

    Ey default% all your /ava programs import the 3ava(lang(Gpac#age% that is why you can use classes li#e String andIntegers inside the program even though you haven2timported any pac#ages(

    The syntaA for importing pac#ages is as follows%

    import nameOfPackage;

    )

  • 8/11/2019 Creating Your Own Classes Sxi

    45/54

    Introduction to Programming 1 45

    )ac,ages:I#porting )ac,ages

    7Aample&

    The first statement imports the specific class Color while theother imports all of the classes in the 3ava(awt pac#age(

    import java.awt.Color;import java.awt.*;

    )

  • 8/11/2019 Creating Your Own Classes Sxi

    46/54

    Introduction to Programming 1 46

    )ac,ages:Creating your own pac,ages

    Suppose we want to create a pac#age where we will placeour Student0ecord class% together with other relatedclasses( 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 insidethis folder(

    *( $dd the following code at the top of the class file(package SchoolClasses;

    public class StudentRecord{. . . .

    )

  • 8/11/2019 Creating Your Own Classes Sxi

    47/54

    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 directorystructure containing the eAecutable classes to match thepac#age hierarchy(

  • 8/11/2019 Creating Your Own Classes Sxi

    48/54

    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 ofrestriction to access these data(

    In /ava% we have what we call access modifiers in order toimplement this(

    Four different types of member access modifiers in /ava& public private protected default(

    !ccess Modifiers:

  • 8/11/2019 Creating Your Own Classes Sxi

    49/54

    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 inthe absence of an access modifier(

    7Aample&public class StudentRecord {

    //default access to instance variableint name;//default access to methodString getName(){

    return name;}

    }

    !ccess Modifiers:

  • 8/11/2019 Creating Your Own Classes Sxi

    50/54

    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 tothe public members of the class(

    7Aample&

    public class StudentRecord {//public access to instance variablepublic int name;

    //public access to methodpublic String getName(){

    return name;}

    }

    !ccess Modifiers:

  • 8/11/2019 Creating Your Own Classes Sxi

    51/54

    Introduction to Programming 1 51

    !ccess Modifiers:protected access

    This specifies that the class members are accessible only tomethods in that class and the subclasses of the class(

    7Aample&public class StudentRecord {

    //protected access to instance variableprotected int name;

    //protected access to methodprotected String getName(){

    return name;}}

  • 8/11/2019 Creating Your Own Classes Sxi

    52/54

    !ccess Modifiers:

  • 8/11/2019 Creating Your Own Classes Sxi

    53/54

    Introduction to Programming 1 53

    !ccess Modifiers:Coding Guidelines

    The instance variables of a class should normally bedeclared private% and the class will 3ust provide accessormethods which are declared as public! to these variables(

  • 8/11/2019 Creating Your Own Classes Sxi

    54/54

    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!