43
1 202.1.9031 18.12.16

202.1 - cs.bgu.ac.ilipc202/wiki.files/Class_Java_7.pdfJava Constructors • A class provides a . special type of methods, known as . constructors, which are invoked to construct objects

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

  • 1

    202.1.9031

    18.12.16

  • Object-oriented programming ( תכנות מונחה עצמים ) involves programming using objects.

    An object )עצם ) represents an entity in the real world that can

    be distinctly identified.

    For example: a student, a desk, a circle, a button can all be viewed as objects.

    An object has a unique identity ( זהות ייחודית ), state, and behaviors.

    The state מצב ) )of an object consists of a set of data fields

    (also known as properties) with their current values.

    The behavior התנהגות ) )of an object is defined by a set of methods.

    Object-Oriented Programming concepts

  • Objects - example

    3

    Object properties

    Object behavior

  • Objects - examples

    Student – properties ?Student – behavior ?

    Robot – properties ?Robot – behavior ?

    lecturer – properties ?lecturer – behavior ?

    4

  • An object has : - unique identity ( זהות ייחודית )- state מצב ) )- behaviors התנהגות ) )

    • state(attributes) consists of a set of data fields(properties) with their current values.

    • behavior(operations) of an object is defined by a setof methods.

    data field 1

    method n

    data field m

    method 1

    (A) A generic object

    ...

    ...

    State (Properties)

    Behavior

    radius = 5

    findArea()

    Data field, State Properties

    Method, Behavior

    (B) An example of circle object

    5

    (B) An example of circle object

    Method, Behavior

    findArea()

    Data field, State Properties

    radius = 5

    (A) A generic object

    State (Properties)

    Behavior

    ...

    method n

    method 1

    data field m

    ...

    data field 1

  • Classes - definitions• In the real world, you'll often find many individual objects all of

    the same kind. There may be thousands of other bicycles in existence, all of the same make and model.

    • Each bicycle was built from the same set of prototype .and therefore contains the same components(אבטיפוס )

    • In object-oriented terms, we say that your bicycle is an instance מופע ) )of the class of objects(מחלקה) known as bicycles. A class is the prototype from which individual objects are created.

    6

  • • Classes ( מחלקות ) examples:– People,books,dogs,cats,cars,airplanes,trains,etc.

    • Instance of a class מופע של מחלקה) )– You, your parents, the book you are reading, the

    car you driveExample: Car class :Property names Method Namesmodel startEngineyear stopEngineColor accelerate

    Classes - examples

    7

  • Instance of a class

    A class is used to define an object.The state (consists of a set of data fields) defines the object,

    and the behavior defines what the object does.

    Class Name: Student Data Fields:

    name is _______ Methods:

    takeCourse

    Student Object 1 Data Fields:

    name is Kerem

    Student Object 2 Data Fields:

    name is Onur

    Student Object 3 Data Fields:

    name is Meltem

    A class template

    Three objects of the Student class

    David Ronit Vered

    Instances of the class Student

    Ronit

    8

    Three objects of the Student class

    A class template

    Class Name: Student

    Data Fields:

    name is _______

    Methods:

    takeCourse

    Student Object 3

    Data Fields:

    name is Meltem

    Student Object 2

    Data Fields:

    name is Onur

    Student Object 1

    Data Fields:

    name is Kerem

  • Instance of a class - example

    9

  • Instances of a class Point - example

    10

    ( 0, 0)(2, 3)(-3, 1)(-1.5, -2.5)

    4 instances of Point class

    Class Point

  • Java ClassesClasses .are constructs that define objects of the same type (מחלקות )

    (Building plan /prototype of similar objects).

    A Java class uses variables ( to define data fields and (משתנים

    methods .to define behaviors (פעולות )public class Point{

    private double x;private double y;

    public void move(double dx, double dy){

    .

    .

    . } public void printPoint(){

    .

    .

    . }// rest methods

    Class variables( properties )

    Class methods

    11

  • Access Specifiers● One of the techniques in OOP is encapsulation ( הכמסה ).

    It concerns the hiding of data in a class and making this class availableonly through methods.

    ● Java allows you to control access to classes, methods, and variables viaaccess specifiers ( הרשאות גישה ).

    ● public גישה פומבית ) ) classes, methods, and variables can be accessed from everywhere.

    ● The private גישה פרטית ) ) keyword denotes that the variable (or method) is hidden from view of any other class.

    public class Point{

    private double x; // x cannot be accessed by any class except class Point

    private double y; // y cannot be accessed by any class except class Point...

    12

  • Objects - creating• A variable can hold a primitive value or a reference to

    an object ( הפניה ). A variable that serves as an object reference must be declared.

    • A class is used to define an object, and the class name can be thought of as the type of an object.

    • To create an object we use the new operator and the act of creating an object is called instantiation יצירת אובייקט) )For example : Point p1 = new Point();

    Name Type Memory Address

    p1 Point 3000

    p1

    x = 0.0

    y = 0.0

    default values

    An object reference variable stores the memory address of an object

  • Java Constructors

    • A class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.

    • Constructor פעולה בונה ) ) is a special kind of methods that are invoked to perform initializing actions - instantiation.For example : Point p2 = new Point(3.5,2,4);

    • Constructors must have the same name as the class itself.

    Name Type Memory Address

    p2 Point 2000

    p2

    x = 3.5

    y = 2.4

    14

  • Constructors - examplepublic class Point{

    private double x;private double y;public Point(double x, double y){

    .

    .

    . } public void printPoint(){

    .

    .

    . }

    // rest methods

    ● Constructors must have the

    same name as the class itself.

    ● Constructors do not have a

    return type — not even void !

    15

  • Constructors – implementation

    public class Point{

    private double x;private double y;

    public Point(double x, double y){

    this.x = x;this.y = y;

    } // Point

    The this keyword is required is when a method argument or a local variable in a method has the same name as one of the data fields of the class.

    Class variables(data fields)

    16

  • Constructor without parameters

    public Point( ){

    this.x = 7.5;this.y = 15.4;

    } // PointName Type Memory

    Address

    p3 Point 1500

    p3

    x = 7.5

    y = 15.4

    public Point( ){

    } // Point

    p3

    x = 0.0

    y = 0.0

    Point p3 = new Point( );

    Choice 1 Choice 2

    17

  • Default Constructor• A class may be declared without constructors.

    • In this case, a default constructor with an empty body isimplicitly declared in the class. This constructor, called adefault constructor ( פעולה בונה ברירת מחדל ),is provided automatically from Java compiler only if noconstructors are explicitly declared in the class.

    ● The default constructor initializes all instance variablesto default value ( zero for numeric types, false for booleans).

    18

  • Accessing the variables of an object• Accessing a class variable through the class by

    specifying the name of the class, followed by a dot operator, followed by the name of the variable.

    For example:Point p1 = new Point();Point p2 = new Point();p1.x = 2.5;p1.y = - 3.9;p2.x = 10;p2.y = p1.y;System.out.println( “p1=“ + p1.x + “,“ + p1.y );

    If access specifiers of x and y class variables arepublic ,class variables can be initialized by anassignment statement.

    This would produce following result:

    p1 = 2.5,-3.9

  • Accessing the methods of an object

    To access the methods of an object, we use the same

    syntax as accessing the data of an object.

    This is why it is called “Object-Oriented"

    Programming( OOP); the object is the focus here,

    not the method call.

    We use an object reference to invoke an

    object's method.

    file testCircle.java

    public class Circle {

    public double x, y; // The coordinatespublic double r; // The radius of circle// Methods that print the circumference and// return the area of the circlepublic void circumference()

    { System.out.println( 2 * 3.14 *this. r); }public double area()

    { return 3.14 * this.r * this.r; } } // Circle

    Circle c = new Circle( );c.x = 2.0;c.y = 2.0;c.r = 1.0; double a = c.area( );c.circumference( );

    fileCircle.java

    20

  • Differences between Variables of Primitive Data Types and Object Types

    1 Primitive type int i = 1 i

    Object type Circle c c reference

    Created using new Circle()

    c: Circle

    radius = 1

    ▪ Reference variables are created using defined constructors of theclasses.

    ▪ They are used to access objects. These variables are declared to be ofa specific type that cannot be changed.

    ▪ Class objects, and various type of array variables come under referencedata type.

    ▪ Default value of any reference variable is null: a reference that does notcurrently point to an object. 21

    c: Circle

    radius = 1

    Created using new Circle()

    reference

    Object typeCircle c c

    Primitive typeint i = 1 i

    1

  • Referenced Data FieldsThe data fields can be of reference types.For example:

    the following Student class contains a data field name of the String type , a data field grades contains a data of the integer arraytype.

    public class Student{

    private String name; // name has default value nullprivate int age; // age has default value 0private boolean isMemberStudComunity; // default value falseprivate int [ ] grades; // student’s grades array has default value nullprivate char gender; // c has default value '\u0000‘

    .

    .

    .} // class Student 22

    Class Student methods

  • Copying Variables of Primitive Data Types and Object Types

    i

    Primitive type assignment i = j Before:

    1

    j

    2

    i

    After: 2

    j

    2

    c1

    Object type assignment c1 = c2 Before:

    c2

    c1

    After:

    c2

    c1: Circle radius = 5

    C2: Circle radius = 9

    c1: Circle radius = 5

    C2: Circle radius = 9

    Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.

    The assignment of one reference to another merely creates another reference to the same object.

    23

    After:

    Primitive type assignment i = j

    j

    2

    i

    2

    j

    2

    1

    Before:

    i

    Object type assignment c1 = c2

    C2: Circle

    radius = 9

    c1: Circle

    radius = 5

    After:

    c2

    c1

    C2: Circle

    radius = 9

    c1: Circle

    radius = 5

    c2

    Before:

    c1

  • Garbage collection● As shown in the previous slide, after the assignment

    statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage.

    ● When the last reference to an object is lost, the objectbecomes a candidate for garbage collection.

    ● Java performs automatic garbage collector ( אספן זבל )by periodically reclaiming the memory space occupiedby these object.

    24

  • Objects As Parameters

    public class Point{

    private double x;private double y;

    public boolean isEgual(Point m){

    return (m.x == this.x && m.y == this.y)} public void printPoint( ){

    System.out.println( “x=“ + this.x+ ” y=“ + this.y);}// rest class Point methods

    public static void main(String[ ] args) {

    Point p1=new Point(2.0,3.0);Point p2=new Point(2.0,3.0);p1.printPoint( );p2.printPoint( );if (p1.isEqual(p2))

    System.out.println( “YES“ );else

    System.out.println( “NO“ );

    } // main

    This program generates the following output:x=2.0 y= 3.0x=2.0 y=3.0YES

    file testPoints.javafile Point.java

    25

  • Copy Constructor• We can define multiple constructors in the class, with each one

    having a different argument list :constructor without parameter list, constructor with parameter list and copy constructor ( פעולה בונה מעתיקה ) with reference type parameter.

    public class Point ( ) {private double x;private double y;

    public Point(double x, double y) {this.x = x;this.y = y; }

    public Point( ) {this.x = 5.0;this.y = 3.0; }

    public Point( Point p) {this.x = p.x;this.y = p.y; }

    // rest class Point methods

    In class Point three methods are created with the same name.

    In Java method overloading ( (העמסהmeans creating more than a single method with same name with different parameters.

    26

    Copy constructor

  • Copy Constructor - examplepublic static void main(String[ ] args){

    Point p1=new Point(2.0,3.0);Point p2=new Point(p1);p1.printPoint( );p2.printPoint( );

    } // main

    This program generates the following output:

    x = 2.0 y = 3.0x = 2.0 y = 3.0

    p1

    x y

    2.0 3.0

    p1p2

    x y

    2.0 3.0

    p2

    Two different instances of the Point object.

  • toString method• The Java toString() method is used when we need a

    string representation of an object.• This method is defined in Object class.

    public class Point{

    private double x;private double y;

    // constructor methodspublic String toString( ){

    String str = ( “x=“ + this.x+ ” y=“ + this.y);return str;

    } // toString

    // rest class Point methods

    public static void main(String[ ] args){

    Point p1 = new Point(2.0,3.0);Point p2 = new Point(4.0,5.0);String s = p1.toString ( );System.out.println(s);// System.out.println(p1.toString());System.out.println(p2);

    } // main

    This program generates the following output:

    x = 2.0 y = 3.0x = 4.0 y = 5.0 28

  • Getter/Setter methods

    • Getter and setter methods are used to retrieve and manipulate private variables in a different class.

    • The difference between getter and setter methods is obvious: a getter method gets the value, a setter method sets the value.

    • The reason to use is because of the principle of information hiding ( הסתרת מידע ) - classes should not reveal their innards to the outside world.This is the most important feature of the Object-Oriented Programming.

  • getter/setter methods - examplepublic class Point {

    private double x;private double y;

    // class Point constructor methodspublic double getX( ){

    return this.x;}public double getY( ){

    return this.y;}public void setX(double x){

    this.x = x;}public void setY(double y){

    this.y = y;}// rest class Point methods

    public static void main(String[ ] args){

    Point p1 = new Point(2.0,3.0);System.out.println(p1.toString());System.out.print( “Enter the x value “ );double newX = reader.nextDouble();p1.setX(newX);System.out.print( “Enter the y value “ );double newY = reader.nextDouble();p1.setY(newY);System.out.println(p1.toString());

    } // main

    This program generates the following output:

    x = 2.0 y = 3.0Enter the x value 4.0Enter the y value 5.0x = 4.0 y = 5.0

    30

  • Class Rational

    31

    ● In mathematics, a rational number is any number that can be expressedas the quotient or fraction a/b of two integers, with the denominator b not equal to zero.

    ● The basic arithmetic operations for rational number are addition,subtraction, multiplication, and division.

    ● Class Rational represents one rational number with a numerator anddenominator.

    So, a rational number looks like this:numerator

    denominator

    ● In Rational Class we examine the following basic operations:

    - Equality- Multiplication- Division

  • Class Rational

    32

    public class Rational {private int x; // numeratorprivate int y; // denominatorpublic Rational (int x, int y) {

    this.x = x;this.y = y;

    } // Rational class constructorpublic int getNumerator() {

    return this.x;} // getNumeratorpublic int getDenom() {

    return this.y; } // getDenomirator

    public void setNumerator( int x) {this.x = x;

    } // setNumeratorpublic void setDenom( int y) {

    this.y = y; } // setDenominator

    Getter methods

    Setter methods

    Constructor

  • Class Rational

    33

    public String toString() {return this.x + "/" + this.y;

    } // toString

    public boolean isEqual(Rational num) {return ( (this.x * num.y) == (num.x * this.y) );

    } // isEqual

    public Rational multiply(Rational num) {return new Rational (this.x * num.x, this.y * num.y);

    } // multiply

    public Rational divide(Rational num) {if (num.y == 0)

    return null;return new Rational(this.x * num.y, this.y * num.x));

    } // divide

    } // Rational

    toString method

    These methods return newRational class variables

  • Class TestRational

    34

    public class TestRational {public static void main(String[ ] args) {

    Rational r1 = new Rational (2,3);Rational r2 = new Rational (4,6);System.out.println("r1: " + r1);System.out.println("r2: " + r2);System.out.println("r1, r2 equal ? " + r1.isEqual(r2)); Rational r3 = r1.multiply(r2);System.out.println("r3 = r1*r2: " + r3);Rational r4 = r1.divide(r2);System.out.println("r4 = r1/r2: " + r4);

    } // main} // class TestRational

    This program generates the following output:

    r1: 2/3r2: 4/6r1, r2 equal ? truer3 = r1*r2: 8/18r4 = r1/r2: 12/12

  • Class variables - definition● When a number of objects are created from the same class

    definition, they each have their own distinct copies of instance variables ( תכונות מופע ) .

    For example :Each Point object has its own values for x and y coordinates variables, stored in different memory locations.

    ● Sometimes, we want to have variables that are common to all objects .This is accomplished with the static modifier.Fields that have the static modifier in their declaration arecalled static fields or class variables (תכונות מחלקה).

    ● Any object can change the value of a class variable.35

  • Class variables - implementationpublic class PointCounter{

    private double x; private double y; private static int numPoints = 0; public PointCounter(double x, double y){

    this.x = x; this.y = y; PointCounter.numPoints++;

    } // constructorpublic static int getNumberOfPoints(){

    return PointCounter.numPoints;} // getNumberOfPoints.. .

    } // class PointCounter

    Increment class variable numPoints to tell anyonethat we have another instance of this class.

    Coordinates - not static, thus not shared amonginstances of PointCounter.

    Keeps track of the number of Point objects created. Since it is static, all Point objects share this variable.

    36

    Rest class PointCounter methods

  • Class variables - implementation, cont.

    37

    This method returns the new middle point of this point and a given as parameter point p of PointCounter class.

    public PointCounter middle(PointCounter p) {

    double middleX = (this.x + p.getX()) / 2;double middleY = (this.y + p.getY()) / 2;return new PointCounter(middleX, middleY);

    } // middle

    This method calculates the distance between this point and a given as parameter point p of PointCounter class.

    public double distance(PointCounter p){

    return (Math.sqrt((Math.pow((this.x - p.getX()), 2) + Math.pow((this.y - p.getY()),2))));

    } // distance

  • Class variables - creation

    p1x y

    2.0 3.0

    p1

    p2x y

    4.0 5.0

    p2

    p3x y

    6.0 7.0

    p3public static void main(String[ ] args){

    PointCounter p1 = new PointCounter(2.0,3.0);PointCounter p2 = new PointCounter(4.0,5.0);PointCounter p3 = new PointCounter(6.0,7.0);

    } // main

    numPoints

    3

    Every instance of the class PointCountershares a class variable, which is in one fixed location in memory.

    38

  • Class TestPointCounter

    39

    public class TestPointCounter{

    public static void main(String[ ] args) {

    PointCounter point1 = new PointCounter(9,9);PointCounter point2 = new PointCounter(5,5);double dis = point1.distance(point2);System.out.println("The distance between the points is :" + dis);PointCounter point3 = point1.middle(point2);System.out.println("The middle point is : " + point3);System.out.println("Number of points is : " + PointCounter.getNumberOfPoints());

    } // main} // TestPointCounter

    This program generates the following output:

    The distance between the points is : 5.65The middle point is : 7.0,7.0Number of points is : 3

  • Constants▪ The static modifier, in combination with the final modifier, is

    also used to define constants.▪ The final modifier indicates that the value of this field cannot

    change.

    For example: the following variable declaration defines a constant named PIstatic final double PI = 3.141592653589793;

    ▪ Constants defined in this way cannot be reassigned.▪ By convention, the names of constant values are spelled in

    uppercase letters.

    40

  • Class (static) methods - definition• The Java programming language supports class (static)

    methods as well as static variables.

    • Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class.

    • A common use for static methods is to access static fields.

    For example: we could add a static method to the PointCounter class to access the numPointsstatic field :

  • Class (static) methods – example 1public class PointCounter{

    private double x; private double y; private static int numPoints = 0;

    // constructorspublic static int getNumPoints( ){

    return PointCounter.numPoints;} // rest class PointCounter methods

    .

    .

    .} // class PointCounter

    public static void main(String[ ] args){

    System.out.println("Num of points : “ + PointCounter.getNumPoints());PointCounter p1 = new PointCounter(2.0,3.0);System.out.println("Num of points : “ + PointCounter.getNumPoints());PointCounter p2 = new PointCounter(3.0,4.0);System.out.println("Num of points : “ + PointCounter.getNumPoints());

    } // main

    This program generates the following output:

    Num of points : 0Num of points : 1Num of points : 2

    NOTE : class method can be invoked with the class name,without the need for creating an instance of the class. 42

  • Class (static) methods – example 2public class TestPointCounter{

    public static int PointsNumber(){

    return PointCounter.getNumPoints();} // PointsNumberpublic static void main(String[ ] args){

    System.out.println("Num of points is: “ + PointsNumber());PointCounter p1= new PointCounter(2.0,3.0);System.out.println("Num of points is: “ + PointsNumber());PointCounter p2 = new PointCounter(3.0,4.0);System.out.println("Num of points is: “ + PointsNumber());

    } // main} // class TestPoint This program generates the following output:

    Num of points is: 0Num of points is: 1Num of points is: 2

    External (static) method

    Main method

    43

    Slide Number 1Object-Oriented Programming conceptsObjects - exampleObjects - examplesSlide Number 5Classes - definitionsClasses - examplesInstance of a classInstance of a class - exampleInstances of a class Point - exampleJava ClassesAccess SpecifiersObjects - creatingJava ConstructorsConstructors - exampleConstructors – implementationConstructor without parametersDefault ConstructorAccessing the variables of an objectAccessing the methods of an objectDifferences between Variables of �Primitive Data Types and Object TypesReferenced Data FieldsCopying Variables of Primitive Data Types and Object TypesGarbage collectionObjects As ParametersCopy ConstructorCopy Constructor - exampletoString methodGetter/Setter methods getter/setter methods - exampleClass RationalClass RationalClass RationalClass TestRationalClass variables - definitionClass variables - implementationClass variables - implementation, cont.Class variables - creationClass TestPointCounterConstantsClass (static) methods - definitionClass (static) methods – example 1Class (static) methods – example 2