02-OOP With Java

Embed Size (px)

Citation preview

  • 8/12/2019 02-OOP With Java

    1/42

    Amir Kirsh

    Object Oriented Programming with Java

    Written by Amir Kirsh

    http://www.google.co.il/imgres?imgurl=http://thesymbianshow.files.wordpress.com/2009/06/322px-java_logosvg.png&imgrefurl=http://thesymbianshow.wordpress.com/2009/06/13/%25D7%2598%25D7%2599%25D7%25A4-%25D7%25A9%25D7%2599%25D7%25A0%25D7%2595%25D7%2599-%25D7%25A8%25D7%2596%25D7%2595%25D7%259C%25D7%2595%25D7%25A6%25D7%2599%25D7%2594-%25D7%25A9%25D7%259C-%25D7%2599%25D7%2599%25D7%25A9%25D7%2595%25D7%259E%25D7%2599-%25D7%2595%25D7%259E%25D7%25A9%25D7%2597%25D7%25A7%25D7%2599-java/&usg=__5sV9BXA5B_N1A79Fvdh4z7-vosE=&h=599&w=322&sz=28&hl=iw&start=1&zoom=1&tbnid=mpdvPW9pstMpEM:&tbnh=135&tbnw=73&ei=dMZXTerdEoG2hAeJvtHbDA&prev=/images%3Fq%3Djava%26um%3D1%26hl%3Diw%26sa%3DN%26rls%3Dcom.microsoft:en-us%26rlz%3D1I7SUNC_en%26tbs%3Disch:1&um=1&itbs=1http://www.google.co.il/imgres?imgurl=http://spagettikoodi.files.wordpress.com/2010/11/java-duke-guitar.png&imgrefurl=http://www.regesh.co.il/2/java-collection%26page%3D2&usg=__Q4XKMM2y6fNsYEllDMVkJ6otPOg=&h=448&w=525&sz=155&hl=iw&start=5&zoom=1&tbnid=-QJzOnVDJFDaKM:&tbnh=113&tbnw=132&ei=dMZXTerdEoG2hAeJvtHbDA&prev=/images%3Fq%3Djava%26um%3D1%26hl%3Diw%26sa%3DN%26rls%3Dcom.microsoft:en-us%26rlz%3D1I7SUNC_en%26tbs%3Disch:1&um=1&itbs=1
  • 8/12/2019 02-OOP With Java

    2/42

  • 8/12/2019 02-OOP With Java

    3/42

    3

    Classes and Objects

    A class will look like this: class MyClass {

    // field, constructor, and method declarations}

    To instantiate an object we will do:

    MyClass instance = new MyClass();

  • 8/12/2019 02-OOP With Java

    4/42

    4

    Accessibility Options

    Example: public class Person {

    private String name; protected java.util.Date birthDate;

    String id; // default accessibility = package public Person() {}

    }

    Four accessibility options: public (default) = package ** protected * private

    * protected is also accessible by package** called also package -private or package -friendly

  • 8/12/2019 02-OOP With Java

    5/42

    5

    Static

    Example:

    public class Widget {static private int counter;static public getCounter() {return counter;}

    }

    int number = Widget.getCounter();

    Static member can be accessed without an instance(same as in C++)

    Called sometimes class variable as opposed to instance variable

  • 8/12/2019 02-OOP With Java

    6/42

    6

    The this keyword

    Example: public class Point {

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

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

    }}

    In Java this is a reference to myself(in C++ it is a pointer )

    The this keyword is also used to call another constructor ofthe same class we will see that later

  • 8/12/2019 02-OOP With Java

    7/42 7

    Defining constants

    Example: public class Thingy {

    public final static doodad = 6; // constant public final id; // constant variable

    public Thingy(int id) {this.id = id;} // OK// public set(int id) {this.id = id;} // error!

    }

    Though const is a reserved word in Javait's actually not in use!However the final keyword let's you defineconstants and const variables

  • 8/12/2019 02-OOP With Java

    8/42

    A

    g e n

    d a All that is to know on class syntax

    Constructors and Initializers Inheritance and Polymorphism

    Interfaces

    Nested Classes

    Enums

    Exercise

  • 8/12/2019 02-OOP With Java

    9/42 9

    Constructors

    Examples in following slides

    Constructors in Java are very similar to C++

    You can overload constructors (like any other method)

    A constructor which doesn't get any parameteris called empty constructor

    You may prefer not to have a constructor at all,in which case it is said that you have by defaultan empty constructor

    A constructor can call another constructorof the same class using the this keyword

    Calling another constructor can be done onlyas the first instruction of the calling constructor

  • 8/12/2019 02-OOP With Java

    10/42 10

    Constructors

    Example 1: public class Person {

    String name = ""; // fields can be initialized!Date birthDate = new Date();

    public Person() {} // empty constructor public Person(String name, Date birthDate) {

    this(name); // must be first instructionthis.birthDate = birthDate;

    }

    public Person(String name) {this.name = name;

    }}

  • 8/12/2019 02-OOP With Java

    11/42

    11

    Constructors

    Example 2: public class Person {

    String name = "";Date birthDate = new Date();

    public Person(String name, Date birthDate) {this.name = name;this.birthDate = birthDate;

    }}

    Person p; // OK p = new Person(); // not good compilation error

  • 8/12/2019 02-OOP With Java

    12/42

    12

    Initializer

    Initializer is a block of instructions performedright after the fields creation and before callingthe constructor

    A class does not have to have an initializer and

    indeed it usually doesn't

    Example: public class Thingy {

    String s;// the block underneath is an initializer{ s="Hello"; }

    } Usually initializer would doa more complex job

  • 8/12/2019 02-OOP With Java

    13/42

  • 8/12/2019 02-OOP With Java

    14/42

    A

    g e n

    d a All that is to know on class syntax

    Constructors and Initializers Inheritance and Polymorphism

    Interfaces

    Nested Classes

    Enums

    Exercise

  • 8/12/2019 02-OOP With Java

    15/42

    15

    Inheritance

    Some Terms

    A class that is derived from another class is called a subc lass (also a derived c lass , extend ed c lass , or ch i ld c lass ).

    The class from which the subclass is derived is called asuperclass (also a base c lass or a parent c lass ).

    Excepting java.lang.Object , which has no superclass,every class has exactly one and only one direct superclass(single inheritance).In the absence of any other explicit superclass, every class isimplicitly a subclass of Object.

    A class is said to be descended from all the classes in itsinheritance chain stretching back to Object.

  • 8/12/2019 02-OOP With Java

    16/42

    16

    Inheritance

    Examples in following slides

    Class Object is the ancestor base class of all classes in Java

    There is no multiple inheritance in Java

    Inheritance is always public thus type is not stated(no private or protected inheritance as in C++)

    Class can implement several interfaces (contracts)

    Class can be abstract

    Access to base class is done using the super keyword

    Constructor may send parameters to its base using the super keyword as its first instruction

    If the base class does not have an empty constructor thenthe class is required to pass parameters to its super

  • 8/12/2019 02-OOP With Java

    17/42

    17

    Inheritance

    Example 1: public class Person {

    private String name; public Person(String name) {

    this.name = name;}// Override toString in class Object

    public String toString() {return name;

    }}

  • 8/12/2019 02-OOP With Java

    18/42

    18

    Inheritance

    Example 1 (cont) : public class Employee extends Person {

    private Employee manager; public Employee(String name, Employee manager) {

    super(name); // must be firstthis.manager = manager;

    }// Override toString in class Person

    public String toString() {

    return super.toString() +(manager!=null? ", reporting to: " + manager :

    " - I'm the big boss!");}

    }

  • 8/12/2019 02-OOP With Java

    19/42

  • 8/12/2019 02-OOP With Java

    20/42

  • 8/12/2019 02-OOP With Java

    21/42

    21

    Inheritance

    Example:

    abstract public class Shape { final public void setFillColor(Color color)

    {}}

    The final keyword is used to forbid a method from beingoverride in derived classes

    Above is relevant when implementing a generic algorithm in thebase class, and it allows the JVM to linkage the calls to themethod more efficiently

    The final keyword can also be used on a class to prevent theclass from being subclassed at all

    of course, final and abstractdont go together (why?)

  • 8/12/2019 02-OOP With Java

    22/42

    A

    g e n

    d a All that is to know on class syntax

    Constructors and Initializers Inheritance and Polymorphism

    Interfaces

    Nested Classes

    Enums

    Exercise

  • 8/12/2019 02-OOP With Java

    23/42

    23

    Interfaces

    Examples in following slides

    Interface is a contract

    An interface can contain method signatures (methods without implementation) and static constants

    Interface cannot be instantiated, it can only be implemented by classes and extended by other interfaces

    Interface that do not include any method signature is calleda marker interface

    Class can implement several interfaces (contracts)

    Class can announce on implementing an interface,without really implementing all of the declared methods,but then the class must be abstract

  • 8/12/2019 02-OOP With Java

    24/42

    24

    Interfaces

    Example 1 using interface Comparable :// a generic max function static public Object max(Comparable... comparables) {

    int length = comparables. length ; if (length == 0) { return null ; } Comparable max = comparables[0];

    for ( int i=1; i

  • 8/12/2019 02-OOP With Java

    25/42

  • 8/12/2019 02-OOP With Java

    26/42

  • 8/12/2019 02-OOP With Java

    27/42

    27

    Interfaces

    Example 4 new IHaveName interface:

    public interface IHaveName {String getName();

    }

    Exercise:

    Create the IHaveName interface andlet class Person implement it

    To allow name investigation we want to create a new IHaveNameinterface:

  • 8/12/2019 02-OOP With Java

    28/42

    A

    g e n

    d a All that is to know on class syntax

    Constructors and Initializers Inheritance and Polymorphism

    Interfaces

    Nested Classes

    Enums

    Exercise

  • 8/12/2019 02-OOP With Java

    29/42

    29

    Nested Classes

    Examples in following slides

    Nested Classes are divided into two categories:static and non-static.

    Nested classes that are declared static are simply calleds ta t ic nested c lasses Non-static nested classes are called inner c lasses

    Inner classes that are defined without having their own nameare called anony m ous c lasses

  • 8/12/2019 02-OOP With Java

    30/42

    30

    Nested Classes

    Example 1: public class OuterClass {

    private int a;static public class InnerStaticClass {

    public int b;}

    public class InnerClass { public void setA(int a1) {

    a = a1; // we have access to a !!!

    }}

    }

  • 8/12/2019 02-OOP With Java

    31/42

    31

    Nested Classes

    Example 1 (cont) :OuterClass.InnerStaticClass obj1 =

    new OuterClass.InnerStaticClass();

    OuterClass.InnerClass obj2 =new OuterClass().new InnerClass();

    obj2.setA(3); // we modify a of OuterClass!!!

  • 8/12/2019 02-OOP With Java

    32/42

    32

    Nested Classes

    Example 2 anonymous class: public interface IHaveName {

    String getName();}

    void someFunction(IHaveName someoneWithName) {System.out.println(someoneWithName.getName());

    }

    public static void main(String[] args) {

    someFunction(new IHaveName() { public String getName() { return "Momo"; }

    });}

  • 8/12/2019 02-OOP With Java

    33/42

    A

    g e n

    d a All that is to know on class syntax

    Constructors and Initializers Inheritance and Polymorphism

    Interfaces

    Nested Classes

    Enums

    Exercise

  • 8/12/2019 02-OOP With Java

    34/42

    34

    Enums

    Examples in following slides

    Structure for Constant Enumeration

    Not an integer! - May represent data (= have fields)- May implement methods (member and static)

    Automatically extends the Enum abstract type

    Cannot extend other Classes or Enums,but can implement interfaces

    Cannot be extended (Enums are final )

  • 8/12/2019 02-OOP With Java

    35/42

    35

    Enums

    Example 1: public class Card {

    public enum Rank { DEUCE , THREE , FOUR , FIVE , SIX , SEVEN , EIGHT , NINE ,TEN , JACK , QUEEN , KING , ACE

    }

    public enum Suit {CLUBS , DIAMONDS , HEARTS , SPADES

    }

    private final Rank rank ; private final Suit suit ;

    private Card(Rank rank, Suit suit) {this . rank = rank;this . suit = suit;

    }

  • 8/12/2019 02-OOP With Java

    36/42

    36

    Enums

    Example 1 (cont) : public class Card {

    public String toString() { return rank + " of " + suit ; }

    private static final List _deck =new ArrayList();

    // Initialize the static deck static {

    for (Suit suit : Suit. values ()) for (Rank rank : Rank. values ())

    _deck .add( new Card(rank, suit)); }

    public static ArrayList newDeck() { // Return copy of prototype deck return new ArrayList( _deck );

    } }

  • 8/12/2019 02-OOP With Java

    37/42

    37

    Enums

    Example 2: public enum Operation {

    PLUS , MINUS , TIMES , DIVIDE ;

    // Do arithmetic op represented by this constant double eval( double x, double y) {

    switch ( this ) { case PLUS : return x + y; case MINUS : return x - y; case TIMES : return x * y; case DIVIDE : return x / y;

    } throw new AssertionError( "Unknown op: " + this );

    } }

  • 8/12/2019 02-OOP With Java

    38/42

  • 8/12/2019 02-OOP With Java

    39/42

    A

    g e n

    d a All that is to know on class syntax

    Constructors and Initializers Inheritance and Polymorphism

    Interfaces

    Nested Classes

    Enums

    Exercise

  • 8/12/2019 02-OOP With Java

    40/42

  • 8/12/2019 02-OOP With Java

    41/42

    41

    Exercise 2

    Write the necessary classes to support the following main:

    static public void main(String[] args) {

    Expression e =

    new Sum(

    new Exponent(new Number(2.0), new Number(3.0)),

    new Sum(

    new Number(1.0), new Number(-3.0)));

    System.out.println(e + " = " + e.evaluate());}

  • 8/12/2019 02-OOP With Java

    42/42

    That concludes this chapter

    amirk at mta ac il

    http://www.comverse.com/http://www.comverse.com/