unit 2 - basic java and object oriented

Upload: theunaxeptable

Post on 09-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    1/31

    9/15/201

    UNIT 2BASIC JAVA & OBJECT ORIENTEDFaculty of Computer Science 2007Universitas Indonesia

    Objectives

    Introduction to Class

    Statement Control in java

    Initialization

    Object creation and lifetime

    Constructor

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    2/31

    9/15/201

    Introduction to Class Diagram

    A class diagram shows the existence of classes and

    their relationships in the logical view of a system

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    3/31

    9/15/201

    Example

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    4/31

    9/15/201

    Javas Control Statement

    Java's syntax is made to mimic C

    Control Statements in Java is similar with C.

    Control Structures

    Two basic types of control structures: Selection: Given one or more possible choices: choose which section (if

    any) of an algorithm to execute.

    Iteration: Repeat a section of an algorithm provided required conditionsare met. Also known as looping.

    Selection Control: The IfThen_Else statement. Provides up to two possible alternatives.

    The Case statement. Provides any number of possible alternatives. Repetition Control:

    while

    dowhile

    for

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    5/31

    9/15/201

    Exercise

    What is the output of the following :

    int k = 100;

    for (int i = 1; i 5; k--)

    {

    System.out.println(k);}

    System.out.println(k + "\n");

    }

    Exercise

    Consider the following commission scheme:

    Create the control statement to determine the

    correct monthly income

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    6/31

    9/15/201

    Exercise

    for(int m = 10; m>5; m--)

    {

    for(int i=0; i target)

    return +1;

    else if(testval < target)

    return -1;

    else

    return 0;

    }

    public static void main(String[] args) {System.out.println(test(10, 5));System.out.println(test(5, 10));System.out.println(test(5, 5));

    }

    }

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    7/31

    9/15/201

    Conditional Operator (? : )

    Javas only ternary operator (takes three operands)

    ? : and its three operands form a conditionalexpression

    Entire conditional expression evaluates to the secondoperand if the first operand is true

    Entire conditional expression evaluates to the thirdoperand if the first operand is false

    Conditional Operator (? : )

    int ternary(int i) {

    return i < 10 ? i * 100 : i * 10;

    }

    int alternative(int i) {

    if (i < 10)return i * 100;

    else

    return i * 10;

    }

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    8/31

    9/15/201

    switch Multiple Selection Statement

    When the expression matches a case, the statements

    in the case are executed until:

    A break statement is encountered or

    The end of the switch statement is encountered

    The default clause is optional

    If the default clause is supplied then it is executed if

    the switch expression does not match any of the case

    constants

    switch Multiple Selection Statement

    switch(c) {case 'a':case 'e':case 'i':case 'o':case 'u': System.out.println("vowel"); break;case 'y':case 'w':System.out.println("Sometimes a vowel");break;default: System.out.println("consonant");

    }

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    9/31

    9/15/201

    Mistakes are easy with switch

    Care must be taken to ensure that the break statements areplaced where they are required. The compiler cannot checkthis for you because the break statement is not required tofollow each case.switch ( choice)

    {

    case Y: case y:

    repeatAgain = true;

    case N: case n:

    repeatAgain = false;

    }

    What is the error in the above statement?

    Corrected Version

    The correct version should be:switch ( choice)

    {

    case Y: case y:

    repeatAgain = true;

    break;case N: case n:

    repeatAgain = false;

    }

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    10/31

    9/15/201

    1

    break and continue Statement

    break/continue

    Alter flow of control

    break statement

    Causes immediate exit from control structure

    Used in while, for, dowhile or switch statements

    continue statement

    Skips remaining statements in loop body

    Proceeds to next iteration Used in while, for or dowhile statements

    break Statement

    1 // Fig. 5.12: BreakTest.java2 // break statement exiting a for statement.3 public class BreakTest4 {5 public static void main( String args[] )6 {7 int count; // control variable also used after loop terminates8

    9 for ( count = 1; count

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    11/31

    9/15/201

    continue Statement

    1 // Fig. 5.13: ContinueTest.java 2 // continue statement terminating an iteration of a for statement. 3 public class ContinueTest4 {5 public static void main( String args[] )6 {7 for ( int count = 1; count

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    12/31

    9/15/201

    1

    Primitive vs Reference Variables

    Primitive variables: Direct access to the data

    Modification of the data involves modification to thecontents of the variable

    Reference variables: Indirect access to the dataModification of the data within an object must be done

    via object method

    Example:frogName = froggie.getName();

    froggie.setName(Kermit);

    Initialization

    What is stored in a variable when it is created?

    Java auto-initializes variables

    Primitive variables:

    Numeric set to zero

    char set to blank

    boolean set to false

    Object variables: Set to null

    null represents an invalid memory address

    Not all programming languages auto-initialize so it is extremely badprogramming practice to rely on auto-initialization

    You should always explicitly initialize variables

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    13/31

    9/15/201

    1

    Initialization and Clean Up

    Many C bugs occur when the programmer forgets to

    initialize a variable. This is especially true withlibraries when users dont know how to initialize a

    library component, or even that they must.

    Cleanup is a special problem because its easy to

    forget about an element when youre done with it,

    since it no longer concerns you.

    Thus, the resources used by that element areretained and you can easily end up running out of

    resources (most notably, memory).

    Order of Initialization

    Within a class, the order of initialization is

    determined by the order that the variables are

    defined within the class.

    The variable definitions may be scattered

    throughout and in between method definitions,but the variables are initialized before any

    methods can be calledeven the constructor

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    14/31

    9/15/201

    1

    Example:

    class Counter {

    int i;

    Counter() { i = 7; }

    // . . .

    The variable i will be first initialized to 0, then to 7.

    This is true with all the primitive types and with objectreferences, including those that are given explicit

    initialization at the point of definition.

    Constructors

    Used to perform any initialization required.

    The name of the constructors must be identical to the name of theclass.

    Even though the constructor is returning a value to the calling module,we do not specify a return type for the method (as it must be apointer to the object).

    When an object is instantiated, storage is allocated and theconstructor is called

    It is guaranteed that an object is initialized before you can use it.

    The object reference returned by the new operator is essentially returned

    by the constructor

    After we have used a constructor to create an object, we call theobject an instance of a class.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    15/31

    9/15/201

    1

    The Constructor

    //: c04:SimpleConstructor.java

    // Demonstration of a simple constructor.

    class Rock {

    Rock() { // This is the constructor

    System.out.println("Creating Rock");

    }

    }

    public class SimpleConstructor {

    public static void main(String[] args) {

    for(int i = 0; i < 10; i++)

    new Rock();

    }

    }

    Like any method, the constructor can have

    arguments.

    The constructor arguments allow you to provide

    initialization parameters when instantiating an

    object

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    16/31

    9/15/201

    1

    //: c04:SimpleConstructor2.java

    // Constructors can have arguments.

    class Rock {

    int myNumber;

    Rock(int i) { // This is the constructor

    myNumber = i;

    System.out.println("Creating Rock No: " + myNumber);

    }

    }

    public class SimpleConstructor {

    public static void main(String[] args) {

    for(int i = 0; i < 10; i++)new Rock(i);

    }

    }

    There may be a variety of ways in which the objectcan be created.

    A constructor should be defined for each case.

    Method overloading is used to select the correctconstructor for each instantiation.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    17/31

    9/15/201

    1

    The Constructor

    // Constructors can be overloaded.

    class Rock {

    int myNumber;

    Rock() { // This is the constructor

    // myNumber is left at 0

    }

    Rock(int i) { // This is the constructormyNumber = i;

    }

    } // end class Rock

    The new operator must call a constructor

    The constructor must both exist and be exposed(remember access control?) or the compiler will givean error

    If you don't code a constructor in the class definition,

    the compiler supplies a default constructor with noarguments

    also called the "no args" constructor

    If you define any constructors, the compiler will notprovide a default!

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    18/31

    9/15/201

    1

    Default Constructor

    //: c04:DefaultConstructor.java

    class Bird {

    int i;

    }

    public class DefaultConstructor {

    public static void main(String[] args) {

    Bird nc = new Bird(); // default!}

    }

    Default Constructor

    // Oops! NoDefaultConstructor.java

    class Bird {

    int wingspan;

    Bird(int i) {

    wingspan = i;

    } // end constructor

    }

    public class NoDefaultConstructor {

    public static void main(String[] args) {

    Bird nc = new Bird(); // Compiler error!

    }

    }

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    19/31

    9/15/201

    1

    Default Constructor

    A constructor which has no parameters is called adefault constructor.

    If a class definition does not include any constructorsthen a default constructor is assumed.

    If a class has not explicitly been defined to inheritfrom a specified super class then it is assumed toinherit from the predefined class java.lang.Object.

    The default constructor for the super class is always

    called prior to executing the constructor for the subclass.

    The Java String Class

    Generally a string is a collection of 1 or more characters

    The Java String class provide us with the facility tohandle strings

    String variables are objects but they can be used as ifthey were primitive variablesString unitName = Design and Programming;

    Can also be treated as an objectString unitName = new String(Design and Programming);

    String can also be concatenated using the plus operator Example: int x=42;

    String message;

    message = x = + x;

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    20/31

    9/15/201

    2

    Exercise

    Create a class with a no-args constructor that

    prints a message.

    Include a main method that instantiates an

    instance of the class.

    Add a constructor that takes a String as an

    argument and prints that.

    Referring to a Object from Within Itself:this

    It is sometimes necessary to for an object to refer to

    itself.

    This is a problem for a Java programmer because

    they need to express this selfreference in the class

    design. i.e. They cannot write the object!

    In the class design, whenever the selfreference is

    required the reserved word this is used.

    When an object is created from the class design then

    this will be replaced by the actual address of that

    object.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    21/31

    9/15/201

    2

    The Two Uses of this

    The two situations where selfreferencing is required are: When the address of this object needs to be passed as a parameter to

    a method which resides outside of the class specification for the object.

    When a Java programmer wishes to name a local method IMPORTparameter with the same name as its corresponding class field.

    Example of when the address of this object needs to bepassed on to some other part of the program:

    An object which will display a GUI has a close button object declaredwithin in it.

    The close button needs a reference to this object so that it can inform it

    when the button has been pressed.

    quitButton.addActionListener( this);

    The this Keyword

    // Simple use of the "this" keyword

    public class Leaf {

    int i = 0;

    Leaf increment() {

    i++;

    return this;

    } // end method increment

    void print() {System.out.println("i="+i);

    public static void main(String[] args) {

    Leaf l = new Leaf();

    l.increment().increment().print();

    } // end method main

    } // end class Leaf

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    22/31

    9/15/201

    2

    The this Keyword

    // Another use of the "this" keyword

    public class Leaf {

    int i = 0; // i is part of the object

    void increment(int i) { // i as local, too

    this.i = this.i + i; // The compiler knows!

    } // end method increment} // end class Leaf

    Constructor Calling Constructor

    When you define a class with several

    constructors, you'd often like to call one

    constructor from another to avoid duplicating

    code.

    A constructor is called using: this You can, using this with an argument list:

    this(); // calls no-args constructor

    this(27); // constructor with numeric arg

    But there are rules!

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    23/31

    9/15/201

    2

    Constructor Calling Constructor

    A constructor can call another constructor only

    in the first statement of the constructor.

    This implies that a constructor can only call one

    other constructor!

    Constructor Calling Constructor

    Modify your class so that the no-args

    constructor, instead of printing a specified

    value, calls the other constructor

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    24/31

    9/15/201

    2

    The Meaning of Static

    Now that we've seen the this keyword, we're more

    able to deal with static .

    Members that are part of a particular object can

    be referenced only with an object reference

    (including this ).

    Members that are part of a class - and shared by

    all objects of that type - are not referred to by

    object reference. Java: Static method and static variable

    C: Global function and global variable

    Static Data Initialization

    When you say something is static, it means that data

    or method is not tied to any particular object instance

    of that class.

    So even if youve never created an object of that class

    you can call a static method or access a piece of static

    data.

    With ordinary, non-static data and methods, you must

    create an object and use that object to access the

    data or method, since non-static data and methods

    must know the particular object they are working with.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    25/31

    9/15/201

    2

    The Meaning of Static

    Because static members exist whether or not

    any object of the type is instantiated, static

    members can reference only other static

    members

    static methods can call only other static methods

    static methods can reference only static variables

    The Meaning of Static

    Static methods are also referred to as "class

    methods", and static variables as "class

    variables, because they are shared by all

    objects in the class.

    Is this a way of cheating on the "everything isobjects" and "there are no globals?" Only until

    you get a more complete understanding of

    how things such as class loading really work.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    26/31

    9/15/201

    2

    Specifying Initialization

    You can specify an initialization expression at the

    point you define a variable.

    class Measurement {

    boolean b = true;

    char c = 'x';

    short s = 0xff;

    int i = 999;

    }

    You can initialize non-primitives in the same way.

    String s = new String("Hello");

    Specifying Initialization

    You can even call a method:

    String s = getDefaultString();

    The method can have arguments, but the arguments

    cannot be other class members that haven't been

    initialized yet.

    Order is important!

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    27/31

    9/15/201

    2

    Order of Initialization

    Static variable initialization

    The first time an object of a given type is

    instantiated, or a static member of that class

    is referenced, the JVM locates the .class

    file and loads it into memory.

    When the class is loaded, all static initializers

    are run in the order they are encountered inthe .class file.

    Order of Initialization

    Explicit static initialization

    Java allows you to group static initializations inside

    a static block:

    static int i;

    static {i = 999;

    }

    This block is executed the first time you instantiate

    an object of the class type, or the first time you

    access a static member of the class.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    28/31

    9/15/201

    2

    Order of Initialization

    Non-static variable allocation and

    initialization.

    Constructor is called.

    Naming Variables, Methods, and Classes

    Programmer constantly has to invent names for classes, methods,variables, constants, etc

    We call these names identifiers

    You need to give considerable thought to every name you createthey are your bricks glued together with the mortar of the operators

    Names should be:

    Unique

    Meaningful

    Unambiguous

    Consistent

    Enhance by case

    There are also reserved words (which are always in lower case):identifiers with special meaning which must be used in predefinedways e.g. class, public, etc

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    29/31

    9/15/201

    2

    Rules for Identifiers

    Consist only of letters, digits, _ or $

    Cannot start with a digit

    Cannot be a reserved word

    Case sensitive, example:

    StNo, stno, STNO, Stno are all different variables

    Can be any length

    Guidelines for Identifers

    Meaningful: give a name that truly reflects the natureof value it hold e.g. studentNo is different tonoOfStudents

    Readable: e.g. studentNo not stdnbr

    Consistent: be consistent in all aspectsabbreviation,case, identation, etc

    Avoid verbosity:identification_Number_Of_The_Student that length is unlimited avoid overly long names

    Use underscore to good effect

    Use capitalization to good effect

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    30/31

    9/15/201

    3

    Java Identifier Naming Convention

    Constants should be completely uppercase Example:public static final int MAXSTUDENTS =30000;

    Class name should be capitalized Example:public class ThisIsAClass

    Methods and variables should be internallycapitalized Example:public void thisIsAMethod();

    private double thisIsAVariable;

    Classes in Java: .java Files and Class Names

    The naming conventions in java specify that a class nameshould be capitalised.

    Each class definition should be in its own .java file.

    The name of the .java file should follow the sameconvention.

    Problems can sometimes arise when using an operating system

    which is not case sensitive (i.e. MSDOS).

    The act of compiling an application will result in a .classfile being generated for each Java class defined. Thisshould mean for each .java file.

    The class files will contain the Java byte code to beinterpreted when the application is run using the Javainterpreter.

  • 8/8/2019 Unit 2 - Basic Java and Object Oriented

    31/31

    9/15/201

    Classes in Java: .java Files and Class Names

    A reasonable size application can have hundreds of .java files!

    This means that you have to stay organised

    Keep all of the .java files for an application in one folder

    DO NOTkeep any .java files which are not associated with theapplication in the folder.

    Name the folder with the same name as the application.

    Much of the Java that you write might be applicable across anumber of applications.

    These general purpose classes should be grouped together in a

    library which is accessible to all of your applications. In Java we call such a library a package.

    Nouns and Verbs

    Like algorithm design, the determination of what classes should be used isstill, by and large, an art form.

    One shallow technique is the nouns and verb approach:

    Nouns are mapped to classes.

    Verbs are mapped to sub modules within classes

    The definition of noun and verb gets stretched to cover collections of words.

    Result is that: sub module names should always describe an action (i.e. getName)

    Class names should always describe a thing (e.g. PersonClass)

    It is important to note that the set of classes proposed will change over thetime the software is being designed.

    This is exactly the same principle as the steps in algorithms changing as thealgorithm is being refined.

    This approach is both shallow and naive but its a very good starting point.