48023 programming fusndamentals

Upload: marco-huang

Post on 03-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 48023 Programming Fusndamentals

    1/30

  • 8/12/2019 48023 Programming Fusndamentals

    2/30

  • 8/12/2019 48023 Programming Fusndamentals

    3/30

    3 | P a g e

    Template for Class Definition

    Import Statements: Include a sequence ofimport statements.

    Comment: Use a comment to describe theprogram

    Class Name: Give a descriptive name to themain class.

    Fields: Method Body: Include a sequence of

    instructions.

    Declare, create, use

    To write an object-oriented program in Java, you must:1. Declare an object name - a name we use to refer to an object2. Create an object - the actual object which the declared name will refer to3. Use an object - by sending messages to it

    Example:Car herbie;

    herbie = new Car(red);

    herbie.accelerate(0.5);

    Object Declaration

    object declaration: designates the name of an object and the class towhich the object belongs to.

    declaring the name herbie, we will use to refer to a Car object. More examples.

    o Object of a BankAccount - BankAccount sv125;o Object of a StudentStudent john,jim,marie;

    Identifiers

    Valid identifiers:Any identifierthat is not reserved for other uses can be used as an object nameo Identifier: is a sequence of letters, digits, underscores (_), and the dollar sign, with the first one being a lettero No spaces are allowed in an identifier.o Java is case sensitive and hence upper- and lowercase letters are distinguished in Java.

    Identifiers >>>> name a class, object, method, and others (variables and constants).o Valid identifier Examples: x123, velocity

    Conventions:o Class names = start with uppercaseo Object names = start with lower case

  • 8/12/2019 48023 Programming Fusndamentals

    4/30

    4 | P a g e

    Object Creation

    To create the actual object, we needto invoke the new operation.

    More examples:o customer = new Customer( );o jon = new Student(John

    Java);

    Declare/create in one line

    Normally, declaring and creating an object is two lines of code:BankAccount myAccount;

    myAccount = new BankAccount();

    (Declare and create merged)BankAccount myAccount = new BankAccount();

    Sending a Message /Invoking a method

    Format: object name.method name(argument);o account.deposit(200.0);o student.setName(john);o car1.startEngine( );

    There is always () after a call to a method. When there is no argument to be passed to the method, there is nothinginside the ().

    calling an objects method = sending a message to an object

    Program 3

    Date

    The Date class from the java.util package is used to represent a date. When a Date object is created, it is set to today (the current date set in the computer)

  • 8/12/2019 48023 Programming Fusndamentals

    5/30

    5 | P a g e

    The class has toString method that converts the internal format to a string.Date today;

    today = new Date( );

    today.toString( );

    results in >>>>> Thu Dec 18 18:16:56 PST 2008

  • 8/12/2019 48023 Programming Fusndamentals

    6/30

    6 | P a g e

    Lecture 2numerical data

    Manipulating Numbers

    In Java, to add two numbers x and y, we writeo x + y

    But addition of the two numbers , we must declare their data type. If x and y are integers, we writeint x, y; (int = data type, x = name used)

    or

    int x;

    int y;

    Variables

    When the declaration is made, memory space is allocated to store the values of x and y. x and y are called variables. A variable has three properties:

    o A memory location to store the value,o

    The type of data stored in the memory location, ando The name used to refer to the memory location.

    A variable only holds one value at a time Sample variable declarations:

    int x;

    int v, w, y;

    Numerical Data Types

    There are six numerical data types: byte, short, int, long, float, and double. Sample (example) variable declarations:

    o int i, j, k;o float numberOne;o long bigInteger;o double bigNumber;

    At the time a variable is declared, it also can be initialized (GIVEN A VALUE).o Example 1, we may initialize the integer variables count and height to 10 and 34 as

    int count = 10, height = 34;

    o Example 2, we may initialise the double variable of x as 10.345double x = 10.345;

    Data Type Precisions

    The six data types differ in theprecision of values they can store

    in memory (range of values that

    can be represented).

    USING INT + DOUBLEFORSUBJECT

  • 8/12/2019 48023 Programming Fusndamentals

    7/30

    7 | P a g e

    Assignment Statements

    We assign a value to a variable using an assignment statement. (END WITHSEMICOLON)

    The syntax is = ;

    A single variable appears to the left of equal symbol and an expression appears to theright.

    Examples:sum = firstNumber + secondNumber;

    average = (one + two + three) / 3.0;

    Primitive Data Declaration and Assignments

    CODE

    int firstNumber, secondNumber; (variables are allocated in memory)

    firstNumber = 234;

    secondNumber = 87;

    STATE OF MEMORY

    Assigning Objects

    CODE

    Customer c1; (allocation to memory)

    c1 = new Customer( ); (assigning of new reference to c1)

    c1 = new Customer( ); (overwriting of reference to c1)

    STATE OF MEMORY

    Notice the content of the variable is not the value itself, as is the case with primitive data, but the address of, orreference to, the memory location where the object data is stored. We use arrows to indicate this memory reference.

    Having Two References to a Single Object

    CODE

    Customer clemens, twain; (allocation to memory)

    clemens = new Customer( ); (assigning of new reference to clemens)

    twain = clemens; (clemens = twain

    Values are assigned to variables

  • 8/12/2019 48023 Programming Fusndamentals

    8/30

    8 | P a g e

    Primitive vs. Reference

    primitive data types= Numerical datao Two non numerical primitive data types are boolean(true or false) and char(for character). char is used to

    represent single character (letter, digit, punctuation marks, and others).

    reference data types= Objects >> contents are addresses that refer to memory locations where the objects areactually stored.

    Qs

    1. The first has two occurrences of variable aThe second and third both attempt to declare a

    variable int,which is a reserved word.

    The fourth has the variable name bigNumberand

    the type double in the wrong order.

    2. Both are illegal because they attempt to declare avariable which has the same name as a variable in

    the first line.

    3. This is the question that is crossed out.4. The second and third lines are invalid. They are

    back to front.

    Arithmetic Operators

    The following table summarizes the arithmetic operators available in Java.

    Integer vs double division

    9/2 4 int

    9%2 1 int

    9.0/2.0 4.5 double

    9.0%2.0 1.0 double

    Arithmetic Expression

    How does the expressiono x + 3 * y

    get evaluated? Answer: x is added to 3*y.

    We determine the order of evaluation by following the precedence rules. A higher precedence operator is evaluated before the lower one. If two operators are the same precedence, then they

    are evaluated left to right for most operators.

    MODULO division + DIVISION = integer division.

    MODULO - looks at the remainder

  • 8/12/2019 48023 Programming Fusndamentals

    9/30

    9 | P a g e

    Precedence Rules

    unary operator just meansnegative numbers e.g. 4 + -3. it

    operates on one operand only.

    If you want to alter the precedencerules, then use parentheses to

    dictate the order of evaluation.

    Type Casting

    If xis a float and yis an int, what will be the data type of the following expression?o x * y

    The above expression is called a mixed expression. The data types of the operands in mixed expressions are converted based on the promotion rules. The promotion rules

    ensure that the data type of the expression will be the same as the data type of an operand whose type has the highest

    precision.

    A casting conversion, or type casting, is a process that converts a value of one data type to another data type.o Two types of casting conversions in Java are implicit and explicit.o An implicit conversion called numeric promotion is applied to the operands of an arithmetic operator.

    Explicit Type Casting

    Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data typeusing the following syntax:

    ( )

    Exampleo (float) x / 3 (Type cast (changes) x to data type float float and then divide it by 3.)o (int) (x / y * 3.0) (Type cast (changes) the result of the expression x / y * 3.0 to int.)

    Implicit Type Casting

    Consider the following expression:o double x = 3 + 5;

    The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (typedouble) beforebeing assigned to x

    Notice that it is a promotion. Demotion is not allowed.o If the two operands are of different types, the smaller type is promoted to the bigger type

    9 + 4.0 promotes to 9.0 + 4.0 1.0/2 promotes to 1.0/2.0 hello + 10 promotes to hello + 10

    Summary of a program

    A program is a sequence of statements.o statement 1;

  • 8/12/2019 48023 Programming Fusndamentals

    10/30

    10 | P a g e

    o statement 2;o statement 3;o statement 4;o statement 5;o statement 6;o statement 7;

    There are only 3 kinds of statement:int a;

  • 8/12/2019 48023 Programming Fusndamentals

    11/30

    11 | P a g e

    Overloaded Operator +

    The plus operator + can mean two different operations, depending on the context. + is an addition if both are numbers. If either one of them is a String, the it is a concatenation. Evaluation goes from left to right.

    output = test + 1 + 2; output = 1 + 2 + test;

    Import Statement

    import statement- allows the program to use classes andtheir instances defined in the designated package.

    Import Statement Syntax and Semantics

    .;

    e.g. dorm.Resident;

    If you need to import more than one class from the same package,

    then instead of using an import statement for every class, you can

    import them all using asterisk notation:

    For example, when we write import java.util.*; then we are importing

    all classes from the java.util package.

    Standard classes

    Learning how to use standard Java classes is the first step toward mastering OOP. Some include:o Scanner (java.util.Scanner)o String (java.lang.String) -STRING . uses double quotes + is sequence of characters. E.g. Marcoo Math (java.lang.Math)o System (java.lang.System)

  • 8/12/2019 48023 Programming Fusndamentals

    12/30

    12 | P a g e

    Standard Output

    Using print of System.out(an instance of the PrintStreamclass) is a simple way to display a result of a computation tothe user.

    standard output window - the console window which displays the result to the user of the program via System.outo EXAMPLE 1

    CODE: System.out.print(I love java); OUTPUT: I love java

    We use the print method to output a value: The print method will continue printing from the end of the currently displayed output.

    o EXAMPLE 2 CODE

    System.out.print(How do you do? );

    System.out.print(My name is );

    System.out.print(Jon Java. );

    OUTPUT: How do you do? My name is Jon Java.

    Displaying Numerical Values

    We use the printand printlnmethods to output numerical data to the standard output. CODE:

    int num = 15;

    System.out.print(num); //print a variable

    System.out.print( ); //print a string

    System.out.print(10); //print a constant

    RESULT: 15 10

    Standard Input

    Using a Scannerobject is a simple way to input data from the standard input System.in, which accepts input from thekeyboard.

    First we need to associate a Scanner object to System.in as follows:importjava.util.Scanner;

    Scanner keyboard;

    keyboard = newScanner(System.in);

    System.inis an instance of the InputStream class that provides only a facility to input 1 byte at a time with its readmethod.

    o Analogous to System.outfor output, we have System.in for input.o System.inaccepts input from the keyboard.

    Reading from Standard Input

    After the Scanner object is set up, we can read data. The following inputs the first name (String):

    System.out.print (Enter your first name: );

    String firstName = keyboard.nextLine();

    System.out.println(Nice to meet you, + firstName + .);

    RESULT:o Enter your first name: Suresh (PRESS ENTER)o Nice to meet you, Suresh.

    CODE

    CODE

  • 8/12/2019 48023 Programming Fusndamentals

    13/30

    13 | P a g e

    Getting Numerical Input

    We can use the same Scanner class to input numerical values too by using its nextIntmethod. To input strings, we use the nextLinemethod of the Scanner class. For instance, to input an int value, we use the

    nextIntmethod. Below is an example of inputting a persons age.

    Scanner keyboard = new Scanner(System.in);int age;

    System.out.print( Enter your age: );

    age = keyboard.nextInt();

    Scanner Methods

    Method Example Explanation

    nextByte( ) byte b = scanner.nextByte( );

    nextDouble( ) double d = scanner.nextDouble( ); Reads a double

    nextFloat( ) float f = scanner.nextFloat( ); Reads a float

    nextInt( ) int i = scanner.nextInt( ); Reads a integar

    nextLong( ) long l = scanner.nextLong( );

    nextShort( ) short s = scanner.nextShort( );

    nextLine( ) String str = scanner.nextLine(); Reads a string

    Input/Output Example

    import java.util.Scanner;

    Scanner keyboard;

    String name;

    keyboard = new Scanner(System.in);

    System.out.println("Hello");

    System.out.print("What is your name? ");

    name = keyboard.nextLine(); // reads a String

    System.out.print("Hello ");

    System.out.println(name);

  • 8/12/2019 48023 Programming Fusndamentals

    14/30

    14 | P a g e

    Template for a method Comment:

    Use a comment to describe the program

    Import Statements:

    Include a sequence of import statements.

    Class Name:

    Give a descriptive name to the main class.

    Method Body:

    Include sequence of instructions.

    Get data by reading it from input - Scanner

    The Math class

    The Math class in the java.lang packagecontains class methods for commonly used

    mathematical functions.

    As with all standard classes, they need to beinputted.

    Some Math Class Methods (INITIALLY DOUBLE)

    Method Description

    max(a.b) The larger of a and b.

    pow(a,b) The power of a to b

    sqrt(a) The square root of a

    log(a) Natural logarithm (base e) of a

    floor(a) The largest whole number less than or equal to a.

    sin(a) The sine of a. (Note: all trigonometric functions are computed in radians)

  • 8/12/2019 48023 Programming Fusndamentals

    15/30

    15 | P a g e

    Lecture 3defining your own class part 1

    Template for Class Definition

    This is the template we use when creatingprogrammer-defined classes.

    o Import statement Include a sequence of import

    statements to import standardclasses from JDK (if required)

    o Class comment Use a comment to describe the

    program

    o Class name Give a descriptive name to the

    main class.

    o Fields describe what an object has

    o Methods (including constructors) Include a sequence of instructions.

    Standard classes

    Learning how to use standard Java classes is the first step toward mastering OOP. Some include:o Scanner (java.util.Scanner)o String (java.lang.String) -STRING . uses double quotes + is sequence of characters. E.g. Marcoo Math (java.lang.Math)o System (java.lang.System)

    Class Declaration and Comment

    A comment - any sequence of text that begins with the marker /* and terminates with another marker */.o NOT VITAL BUT , helps readers of the code understand what is going on

    SYNTAX FOR CLASS DECLARATION .class Classname

    {

    }

    Comments :o state the purpose of the programo explain the meaning of code,

    Follow the naming conventions while naming a class and give it a meaningful name.

    Data Member (field) Declaration

    FIELDS - describe what an object has The syntax is:

    o ;

  • 8/12/2019 48023 Programming Fusndamentals

    16/30

    16 | P a g e

    Method Declaration

    methods - what an object cando.

    void () {

    }

    Constructor (special method)

    constructor - a special method that is executed when a new instance of the class is created.o intialises the fields to a valid state. (DEFINES what happens at the moment a new object is created.)o Name of constructor = name of classo No return type

    The syntax is ()

    {

    }

    For example,

    Car herbie = new Car();

    When the above statement is executed, it executes the

    constructor method shown below

    Car ()

    {

    position = 0;

    }

    THE CONSTRUCTOR initialises position (of herbie object) to

    0

  • 8/12/2019 48023 Programming Fusndamentals

    17/30

  • 8/12/2019 48023 Programming Fusndamentals

    18/30

    18 | P a g e

    Self- method calls

    An object may invoke a method on another object (an object of another class):otherObject.someMethod();

    herbie.drive();

    An object may also invoke a method on itself: (SAME CLASS)this.someMethod();

    // OR //

    someMethod();

    For example, the method calls within the showEverything() method of Circle class.

    Approach 1 (CALL FROM DIFF CLASS) Approach 2 (CALL FROM SAME CLASS)

    void showEverything() {

    System.out.println(Showing all);

    this.showRadius();

    this.showDiameter();

    this.showCircumference();

    this.showArea();

    }

    void showEverything() {

    System.out.println(Showing all);

    showRadius();

    showDiameter();

    showCircumference();

    showArea();

    }

    Approach 2 is most commonly used.

    Local variables

    An instance variable exists forthe lifetime of the

    object/instance.

    A local (temporary) variableexists for the lifetime of the

    method invocation and is used

    for storing temporary results

    For example, public double convert(int num) {

    double result;result = Math.sqrt(num

    * num)

    return result;

    }

    FIELD DECLARATION = VARIABLEDECLARATION = field

    Instance value given within the constructor + declared in the class and not in the method

  • 8/12/2019 48023 Programming Fusndamentals

    19/30

    19 | P a g e

    Static fields

    A static field is a property of theclass,

    o there is no need tocreate an instance

    It can be done by:class name.field name

    class name.method

    name

    Static example

    1. (Top EXAMPLE) EachBankAccount object

    shares the same

    interest rate.

    2. (BOTTOM EXAMPLE)Each BankAccount

    has a different

    current balance.

    Sample Instance Data Value (non-static fields)

    All two BankAccount objects possess the instance datavalue current balance.

    The actual dollar amounts are, of course, different.

    Sample Class Data Value (static fields)

    Here we see that a single class datavalue named minimum balance is

    shared by all instances.

  • 8/12/2019 48023 Programming Fusndamentals

    20/30

    20 | P a g e

    Object Icon with Class Data Value

    When the class icon is not shown, we include the class data value in the object iconitself.

    When we do not include the class icon in a diagram, we can use this notation. Whether the data value name is underlined or not indicates the information is a class

    or an instance data value.

    Constants

    Make a field constant using keyword final. Use static also if the value is identical for all objects.

    class Circle

    {

    staticfinaldouble PI = 3.141592654;

    double radius;

    ..METHOD HeRe.

    }

    Constants:o make your code more readable/maintainable.o are conventionally UPPERCASE with an underscore (_) separating each word

    Math.PI is a static/final constant of class Math

    Static methods

    A static method belongs to the class, rather than an object. Math.pow(), Math.sqrt() etc. are all static methodsbelonging to class Math.

    A java program should have a static method called main:public static void main(String[] args) {

    System.out.println(Program starting...);

    Car myCar = new Car();

    myCar.start();

    }

    This is the method (main method) that will be invoked when the user double-clicks on your program.o The main method should create all of your objects and kickstart your program.o You can directly invoke the method on this class by using the syntax Classname.method name

  • 8/12/2019 48023 Programming Fusndamentals

    21/30

    21 | P a g e

    Calling a Class Method (static methods)

    The maximum speed of all MobileRobotobjects is the same. Since the result is the

    same for all instances,

    we define getMaximumSpeedas a classmethod and access it as

    MobileRobot.getMaximumSpeed();

    General Idea: You define an instance methodfor a task that relates uniquely to individual instances (like getCurrentSpeed and getObstacleDistance(), which is

    different for individual mobile robots) and a class method for a task that relates to all instances of the class collectively

    (like getMaximumSpeed(), which is the same for all

    Calling an Instance Method (non-static methods)

    The distance from an obstacle is different forevery MobileRobot object. Since the result is

    different for all instances, we define

    getObstacleDistance as an instance method.

    General Idea: You define an instance method fora task that relates uniquely to individual

    instances (like getCurrentSpeed() and

    getObstacleDistance(), which is different for

    individual mobile robots) and a class method for

    a task that relates to all instances of the class collectively (like getMaximumSpeed(), which is same for all mobile robots).

    Changing Any Class to a Main Class

    Any class can be set to be a main class.o All you have to do is to include the main method.o When we create a program, we must designate one class as the programs main class.

    Any class can include the main methodo the one we designate as the main class includes the main method

    class Motorbike {

    //definition of the class as shown before comes here

    //The main method that shows a sample

    //use of the Motorbike class

    public static void main(String[] args) {

    Motorbike bike;

    bike = new Motorbike();

    bike.drive();

    }

    ...

    }

  • 8/12/2019 48023 Programming Fusndamentals

    22/30

    22 | P a g e

    The main() method

    The main method >> the VITAL entry point into your programo . It should create the first object, and direct the other parts of your program to run in the order in which you

    want to run them.

    Themain methodis the first method, which the Java Virtual Machine executes. When you execute a class , the runtimesystem starts by calling the class's main()method. The main()method then calls all the other methods required to run

    your application.

    public static void main(String[] args)

    {

    }

    Three Types of Comments

    Type of comment example

    Multiline comment

    (BEGINNING + END

    MARKER)

    /*

    This is a comment with

    three lines of

    text.

    */

    Single line comments

    (//)

    // This is a comment

    // This is another comment

    // This is a third comment

    Javadoc comments

    (/** marker and end with

    the */ marker)

    /**

    * This class provides basic clock functions. In addition

    * to reading the current time and todays date, you can

    * use this class for stopwatch functions.

    */

    Composition

    A program usually consists of several classes. For example, if a car consists of a fuel tank and 4 wheels, we have 6 objects and 3 classes:

    o Car (1 object)o FuelTank (1)o Wheel (4)

    Because the Car object contains all of the other objects, we say that the Car is composed of a fuel tank and 4wheels.

  • 8/12/2019 48023 Programming Fusndamentals

    23/30

    23 | P a g e

    CompositionCar example

    Drive method is updated to invoke the roll method on each of the four wheels. And that is how the car moves forwardand the position of each wheel is updated by 1.

    the Car constructor initialises the position of four wheels and creates a fuel tank as soon as a new object is created.

    FIELDS AND METHODS TASKS

    QUestion Fields Methods

    You have been contracted to develop software for a university to keep track of

    student information, enrolments and grades.

    o name,o DOB,o subjects,o grades

    o changeNameo enrolo withdrawo graduate

    You are developing a diagram drawing tool. In the first release, the user will be

    able to draw diagrams consisting only of rectangles, which may be arranged

    within the diagram after they have been drawn.

    This program might have a Diagram class and a Rectangle class.

    o xo yo widtho height

    o resizeo moveo changeColouro

  • 8/12/2019 48023 Programming Fusndamentals

    24/30

    24 | P a g e

    Lecture 4defining your own class part 2

    Method Parameters

    void ( ){

    }

    Adding parameters to class CarEXAMPLE

    Passing arguments to parameters

  • 8/12/2019 48023 Programming Fusndamentals

    25/30

  • 8/12/2019 48023 Programming Fusndamentals

    26/30

    26 | P a g e

    Constructor parameters

    Parameters - allow the caller of that method or constructor to pass in different values to control what they want themethod or constructor to do. If there are no parameters, you are giving the caller no choices. E.g..

    o Car herbie = new Car(4.0); //Initial position of the caro Account myAccount = new Account(1000.0); //Initial bank balanceo Rectangle r = new Rectangle(10.0, 5.0);// initial height and initial width

    Declaring constructor parameters

    Returning methods

    the user of this function has complete control over what is to be done with the returned value ( ){

    Two kinds of method

    Two types of methods:

    procedure - method that performs some action but returns nothing function - method that affects nothing, but returns a value

    Procedure Function

    void deposit(double amount)

    {

    balance = balance + amount;

    }

    double cube(double n)

    {

    return Math.pow(n,3);

    }

  • 8/12/2019 48023 Programming Fusndamentals

    27/30

  • 8/12/2019 48023 Programming Fusndamentals

    28/30

  • 8/12/2019 48023 Programming Fusndamentals

    29/30

    29 | P a g e

    Multiple Instances

    Multiple instances of an object can be created EACH instance of a class has their own variable.

    Class Diagram for Bicycle

    CLASS DIAGRAM

    Class name and data type of an argument passed to the method.

    Passing Objects to a Method

    In a method, for its arguments, we can pass:

    int values double values objects (reference name OR STRING)

    Passing a Student Object

    In the diagram

    1. Argument is passed2. Value is assigned to the data member

    Local, Parameter & Field

    An identifier appearing inside a method can be a local variable, a parameter, or a field. The rules are

    o If theres a matching local variable declaration or a parameter, then the identifier refers to the local variable orthe parameter.

    o Otherwise, if theres a matching data member declaration, then the identifier refers to the data member. o Otherwise, it is an error because theres no matching declaration.

  • 8/12/2019 48023 Programming Fusndamentals

    30/30