Lecture 3
This presentation is the property of its rightful owner.
Sponsored Links
1 / 33

Lecture 3 PowerPoint PPT Presentation


  • 81 Views
  • Uploaded on
  • Presentation posted in: General

Lecture 3. Introduction. Java is a true OO language -the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines the “state” and “ behaviour ” of each object made from the class.

Download Presentation

Lecture 3

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Lecture 3

Lecture 3


Introduction

Introduction

  • Java is a true OO language -the underlying structure of all Java programs is classes.

  • Everything must be encapsulated in a class

    • that defines the “state” and “behaviour” of each object made from the class.

  • A class essentially serves as a template for an object and behaves like a basic data type, e.g., “int”.

  • It is therefore important to understand:

    • how the properties (fields) and methods are defined in a class

    • how they are used to build a Java program


Classes

Classes

  • Contains definition for all Objects of the same type

    • defines the data types and names of properties

    • defines methods that define behavior

    • the “template” for all Object instances of the same type


Classes1

Classes

  • The basic syntax for a class definition:

  • Bare bone class – no fields, no methods

  • classClassName {

    • [fields declaration]

    • [methods declaration]

  • }

  • public class Circle {

    // my circle class

    }


    Classes2

    Classes


    Adding properties fields

    Adding Properties (Fields):

    • Add fields

    • public class Circle {

      • double radius; // radius of the circle

    • double x, y; // center coordinate

    • }


    Constructors

    Constructors

    Constructors are methods that are invoked to construct objects.

    Circle() {

    }

    Circle(double newRadius) {

    radius = newRadius;

    }

    Notice: no return value – these are not methods! These are constructors. They make a Circle object.


    Adding methods

    Adding Methods

    • A class with only data fields has no life.

      • Objects created from such a class cannot respond to anything.

    • Methods are declared inside the body of the class and after the declaration of data fields and the constructors.

    • The general form of a method declaration is:

    type MethodName (parameter-list)

    {

    Method-body;

    }


    Adding methods to class circle

    Adding Methods to Class Circle

    public class Circle {

    double radius; // radius of circle

    double x, y; // centerof the circle

    //Methods to return circumference and area

    public double circumference() {

    return (2*Math.PI*radius);

    }

    public double area() {

    return (Math.PI* Math.pow(radius,2));

    }

    }

    Method Body


    Data abstraction

    Data Abstraction

    • Declare the Circle class, have created a new data type – Data Abstraction

    • Can define variables (objects) of that type:

      Circle aCircle;

      Circle bCircle;


    Creating circle objects cont

    Creating Circle objects cont.

    Circle aCircle;

    Circle bCircle;

    • aCircle, bCircle simply refers to a Circle object, not an object itself. (e.g., this is going to be a Circle, but it isn’t yet.)

    aCircle

    bCircle

    null

    null

    Points to nothing (Null Reference)

    Points to nothing (Null Reference)


    Creating objects of a class

    Creating objects of a class

    • Objects are created using the new keyword.

    • aCircle and bCircle refer to Circle objects

    aCircle = new Circle() ;

    bCircle = new Circle() ;


    Creating objects of a class1

    Creating objects of a class

    aCircle

    aCircle

    P

    P

    aCircle = new Circle();

    bCircle = new Circle() ;

    bCircle = aCircle;

    Before Assignment

    Before Assignment

    bCircle

    bCircle

    Q

    Q


    Automatic garbage collection

    Automatic garbage collection

    Q

    • The object does not have a reference and cannot be used in future.

    • The object becomes a candidate for automatic garbage collection.

    • Java automatically collects garbage periodically and releases the memory used to be used in the future.


    Accessing object circle data

    Accessing Object/Circle Data

    ObjectName.VariableName

    ObjectName.MethodName(parameter-list)

    Circle aCircle = new Circle();

    aCircle.x = 2.0; // initialize center and radius

    aCircle.y = 2.0;

    aCircle.radius = 1.0;


    Executing methods in object circle

    Executing Methods in Object/Circle

    • Using Object Methods:

    sent ‘message’ to aCircle

    Circle aCircle = new Circle();

    double area;

    aCircle.r = 1.0;

    area = aCircle.area();


    Using circle class

    Using Circle Class

    // Circle.java: Contains both Circle class and its user class

    //Add Circle class code here

    class MyMain

    {

    public static void main(String[] args) {

    Circle aCircle; // creating reference

    aCircle = new Circle(); // creating object

    aCircle.x = 10; // assigning value to data field

    aCircle.y = 20;

    aCircle.radius = 5;

    double area = aCircle.area(); // invoking method

    double circumf = aCircle.circumference();

    System.out.println("Radius="+aCircle.r+" Area="+area);

    System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);

    }

    }

    Radius=5.0 Area=78.5

    Radius=5.0 Circumference =31.400000000000002


    Encapsulation

    Encapsulation

    • An object instance owns its state and behavior

    • Java provides access modifiers to define what code can access an object's state and behavior

      • public

        • all code can access the tagged state or behavior

      • private

        • only instances of the enclosing class may access this tagged state or behavior

      • (default) package private

      • protected


    Example of public vs private

    Example of public vs private:

    public class FT {

    privatedouble rad;

    privatedouble circ;

    privatedouble area;

    publicFT() {

    rad = 1.0;

    setValues();

    }

    publicFT(double r) {

    rad = r;

    setValues();

    }

    privatevoid setValues(){

    circ = Math.PI * 2 * rad;

    area = Math.PI * Math.pow(rad, 2);

    }

    publicvoid setrad(double r) {

    rad = r;

    setValues();

    }

    publicString printcirc(){

    String s = "Radius: "+rad+" Cicumference: "+circ+" Area: "+area;

    return s;

    }

    }


    Static variables and methods

    Static Variables and Methods

    Static variables belong to a Class

    • similar to global variables

    • Use mostly for constants

      • easy to create bugs and undefined behavior

        Static methods belong to a Class

    • do not have access to object state (object variables, or fields)

    • cannot call instance methods (because they use object variables)

    • often have good uses as simple functions

      • formulas common to all objects in a Class are often written in a static method

        • Utility classes – think of the java.util… that we’ve imported – has methods we want to be able to use without having the methods attached to an object.


    Instance variables and methods

    Instance Variables, and Methods

    (variables and methods without "static")

    Instance variables belong to a specific instance.Instance methods are invoked by an instance of the class.


    Static fields and methods

    public class mainclass {

    public static void main(String[] args){

    Creature Fluffy = new Creature (3);

    System.out.println(Creature.NumberinHerd());

    System.out.println(Fluffy.getMood());

    Creature Bob = new Creature(0, "Bob");

    System.out.println(Creature.NumberinHerd());

    System.out.println(Bob.getMood());

    Creature Killer = new Creature("Killer");

    System.out.println(Creature.NumberinHerd());

    System.out.println(Bob.getMood());

    }

    }

    Static fields and methods

    public class Creature {

    private intcurrentmood = 2;

    private String name = "Noname";

    private staticintcreaturecount = 0;

    private String[] moods = {"massively depressed","boredstiff","marginally happy", "ecstatic"};

    public Creature() {

    creaturecount++;

    }

    public Creature(int mood) {

    currentmood = mood;

    creaturecount++;

    }

    public Creature(String Creaturename) {

    name = Creaturename;

    creaturecount++;

    }

    public Creature(int mood, String Creaturename) {

    currentmood = mood;

    name = Creaturename;

    creaturecount++;

    }

    public String getMood() {

    return (name +"'s current mood is "+moods[currentmood]);

    }

    public static String NumberinHerd(){

    return ("The current number of creatures is " + creaturecount);

    }

    }


    Accessors and mutators

    Accessors and Mutators

    • Accessors (e.g., getField)

      • public instance methods that access private data

      • may return different forms of the data

      • simple convention: getSomeProperty()

    • Mutators (e.g., setField)

      • public instance methods that change private data

      • may change more than one private data element

      • simple convention: setSomeProperty(x)

        Why are these good ideas?


    Lecture 3

    public class FT {

    private double rad;

    private double circ;

    private double area;

    public FT() {

    rad = 1.0;

    setValues();

    }

    public FT(double r) {

    rad = r;

    setValues();

    }

    public void setrad(double r) { // Mutator – sets (mutates) value

    rad = r;

    setValues();

    }

    public double getrad() { //Accessor – gets (returns) value

    return(rad);

    }

    private void setValues(){

    circ = Math.PI * 2 * rad;

    area = Math.PI * Math.pow(rad, 2);

    }

    public getcirc() {

    return(circ);

    }

    }


    The null value

    The null Value

    If a data field of a reference type does not reference any object, the data field holds a special literal value, null. (null reference value)

    Example:

    Circle circle1 = new Circle(5.0);

    Circle circle2 = null;

    System.out.println(circle1.getrad()); // what happens here?

    System.out.println(circle2.perimeter()); // here?

    circle2 = circle1; // what happens here?

    System.out.println(circle2.perimeter()); // here?

    circle2.setrad(4.2);

    System.out.println(circle1.getrad()); //


    2d arrays

    2D Arrays

    • one-dimensional arrays to model linear collections of elements.

    • two-dimensional arrays represent a matrix or a table

    • Example:


    2 d arrays

    2-D Arrays

    • Make a one-dimensional array of integers:

      int[] arr1d = {3,2,4,1,5};

      • How many elements in the array? (arr1d.length?)

      • How do you access the element at index 3?

    • Now make an array that consists of arrays of ints:

      • int[][] arr2d = {{1,2,3,4},{5,6,7,8},{9,10,11,12}} ;

      • Or (if we don’t know the values:

      • int[][] arr2d = new int[3][4];

  • Can you make an array of arrays of arrays? (a 3-Dimensional array?)


  • Two dimensional array illustration

    Two-dimensional Array Illustration

    arr.length?

    arr[0].length?

    What data type is arr[2] ?


    Lengths of two dimensional arrays

    Lengths of Two-dimensional Arrays

    int[][] x = new int[3][4];


    Quickly more on null references

    (Quickly) More on Null references:

    • A null reference is a pointer to nothing.

      • Pointers = space for address in memory

        • Think of RAM, with each space in memory having its own unique address. (different spaces in memory do different things)

          Circle x;

      • x is now a “null pointer”

        • Meaning x can hold an address for a space in memory that is where a Circle will be, but currently it’s just empty

          x = new Circle();

        • Makes a space for a circle object in memory

          • memory space holds radius, circumference, area fields

          • Holds getRadius() method, SetValues() method,etc.

        • x now holds the address of this new circle in memory.

          • It “points to” the circle in memory


    Matrices making arrays of arrays

    Matrices: Making Arrays of Arrays

    1. double[][] mat = new double[5][];

    What have I just made?

    an array of 5 addresses (that will eventually point to arrays of doubles).

    If I can’t do this:

    2.double[][] mat = new double [][]?

    Why can I do #1?


    To create an array of arrays

    To create an array of arrays:

    You can do:

    double[][] mat = {{3.2,4.1,2.5},{7.1,8.2,9.3}};

    Or

    double[][] mat = new double[3][];

    mat[1] = new double[] {3.1,2.4};

    Or

    double[][] mat = new double[3][];

    double[] arr = {7.2,3.1,2.4};

    mat[2] = arr;

    Or

    double[][] mat;

    mat = new double[][] {{3.2,4.1,2.5},{7.1,8.2,9.3}};


  • Login