creating your class and encapsulation

Upload: torjack

Post on 30-May-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Creating Your Class and Encapsulation

    1/33

    Introduction to Programming 1 1

    Creating your class andEncapsulation

  • 8/14/2019 Creating Your Class and Encapsulation

    2/33

    Introduction to Programming 1 2

    ObjectivesAt 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

  • 8/14/2019 Creating Your Class and Encapsulation

    3/33

    Introduction to Programming 1 3

    Defining your own classesThings to take note of for the syntax defined in this section:

    * means that there may be 0 or more

    occurrences of theline where it was applied to.

    indicates that you have to substitute anactual value for

    this part instead of typing it as it is.

    [ ] indicates that this part is optional

  • 8/14/2019 Creating Your Class and Encapsulation

    4/33

    Introduction to Programming 1 4

    Defining your own classesTo define a class, we write:

    class {

    *

    *

    *

    } where

    is an access modifier, which may be combined with other types of modifier.

  • 8/14/2019 Creating Your Class and Encapsulation

    5/33

    Introduction to Programming 1 5

    Examplepublic 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

  • 8/14/2019 Creating Your Class and Encapsulation

    6/33

    Introduction to Programming 1 6

    Coding GuidelinesThink of an appropriate name for your class. Don't just callyour 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 asyour class name.

  • 8/14/2019 Creating Your Class and Encapsulation

    7/33

    Introduction to Programming 1 7

    Declaring AttributesTo declare a certain attribute for our class, we write,

    [=

    ];

  • 8/14/2019 Creating Your Class and Encapsulation

    8/33

    Introduction to Programming 1 8

    Instance Variablespublic 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 aboutaccessibility later.

  • 8/14/2019 Creating Your Class and Encapsulation

    9/33

    Introduction to Programming 1 9

    Coding GuidelinesDeclare all your instance variables on the top of the classdeclaration.

    Declare one variable for each line.

    Instance variables, like any other variables should start with aSMALL letter.

    Use an appropriate data type for each variable you declare.

    Declare instance variables as private so that only classmethods can access them directly.

  • 8/14/2019 Creating Your Class and Encapsulation

    10/33

    Introduction to Programming 1 10

    Class (static) variablespublic 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 staticvariable.

  • 8/14/2019 Creating Your Class and Encapsulation

    11/33

    Introduction to Programming 1 11

    Declaring MethodsTo declare methods we write,

    (*) {*

    } where,

    can carry a number of different modifiers can be any data type (including void)

    can be any valid identifier

    ::= [,]

  • 8/14/2019 Creating Your Class and Encapsulation

    12/33

    Introduction to Programming 1 12

    EncapsulationThe principle of hiding design or implementationinformation that are not relevant to the current object.

    To encapsulate the property, two methods are used:Setter or Accessor with the pattern of,

    public void set

    ( value) {

    . . . }

    getter or Mutator with the pattern of,

    public < PropertyType >get () {

    . . . }

  • 8/14/2019 Creating Your Class and Encapsulation

    13/33

    Introduction to Programming 1 13

    Accessor MethodsAccessor methods

    used to read values from our class variables (instance/static). usually written as:

    get It also returns a value.

  • 8/14/2019 Creating Your Class and Encapsulation

    14/33

    Introduction to Programming 1 14

    Example 1public 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 shouldreturn a value of type String

    getName - the name of the method

    () - this means that our method does not have any parameters

  • 8/14/2019 Creating Your Class and Encapsulation

    15/33

    Introduction to Programming 1 15

    Example 2public class StudentRecord {

    private String name;:

    public double getAverage(){

    double result = 0;result=(mathGrade+englishGrade+science

    Grade)/3;return result;

    }}

  • 8/14/2019 Creating Your Class and Encapsulation

    16/33

    Introduction to Programming 1 16

    Mutator MethodsMutator Methods

    used to write or change values of our class variables(instance/static).

    Usually written as:

    set

  • 8/14/2019 Creating Your Class and Encapsulation

    17/33

    Introduction to Programming 1 17

    Examplepublic 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

  • 8/14/2019 Creating Your Class and Encapsulation

    18/33

    Introduction to Programming 1 18

    Multiple return statementsYou can have multiple return statements for a method aslong as they are not on the same block.

    You can also use constants to return values instead of variables.

  • 8/14/2019 Creating Your Class and Encapsulation

    19/33

    Introduction to Programming 1 19

    Examplepublic 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/14/2019 Creating Your Class and Encapsulation

    20/33

    Introduction to Programming 1 20

    Static methodspublic 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 methodStudentRecord.getStudentCount()

    int- is the return type of the method. This means that the method should return avalue of type int

    getStudentCount- the name of the method

    ()- this means that our method does not have any parameters

  • 8/14/2019 Creating Your Class and Encapsulation

    21/33

    Introduction to Programming 1 21

    Coding GuidelinesMethod 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 seeexample.

  • 8/14/2019 Creating Your Class and Encapsulation

    22/33

    Introduction to Programming 1 22

    Source Code for class

    StudentRecordpublic 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;

  • 8/14/2019 Creating Your Class and Encapsulation

    23/33

    Introduction to Programming 1 23

    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;}

  • 8/14/2019 Creating Your Class and Encapsulation

    24/33

    Introduction to Programming 1 24

    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(){

  • 8/14/2019 Creating Your Class and Encapsulation

    25/33

    Introduction to Programming 1 25

    Sample Source Code that

    uses 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/14/2019 Creating Your Class and Encapsulation

    26/33

    Introduction to Programming 1 26

    Program OutputAnna

    Student Count = 0

  • 8/14/2019 Creating Your Class and Encapsulation

    27/33

    Introduction to Programming 1 27

    this referenceThe this reference

    used to access the instance variables shadowed by the parameters.

    To use the this reference, we type,

    this.

    NOTE: You can only use the this reference for instance variables andNOT static or class variables.

  • 8/14/2019 Creating Your Class and Encapsulation

    28/33

    Introduction to Programming 1 28

    Examplepublic void setAge( int age ){

    this.age = age;

    }

  • 8/14/2019 Creating Your Class and Encapsulation

    29/33

    Introduction to Programming 1 29

    Overloading MethodsMethod overloading

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

    can be used when the same operation has differentimplementations.

    Always remember that overloaded methods have thefollowing properties:

    the same name different parameters return types can be different or the same

  • 8/14/2019 Creating Your Class and Encapsulation

    30/33

    Introduction to Programming 1 30

    Examplepublic 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/14/2019 Creating Your Class and Encapsulation

    31/33

    Introduction to Programming 1 31

    Examplepublic 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());

    }

  • 8/14/2019 Creating Your Class and Encapsulation

    32/33

    Introduction to Programming 1 32

    Outputwe 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.0English Grade:95.5

    Science Grade:100.0

  • 8/14/2019 Creating Your Class and Encapsulation

    33/33

    Introduction to Programming 1 33

    SummaryDefining your own classesDeclaring Fields (instance, static/class)

    Encapsulation

    Declaring Methods (accessor, mutator, static)

    Returning values and Multiple return statements

    The this reference

    Overloading Methods