OOP Lecture 10

download OOP Lecture 10

of 22

Transcript of OOP Lecture 10

  • 7/28/2019 OOP Lecture 10

    1/22

    Object-Oriented Programming

    Lecture 10Dr. Zareen Fawad

    Department of Computer Science

    COMSATS Institute of InformationTechnology, Wah

  • 7/28/2019 OOP Lecture 10

    2/22

    Overview

    Inheritance

    Abstract classes

    Interfaces Polymorphism

    Exception Handling

  • 7/28/2019 OOP Lecture 10

    3/22

    Inheritance

    Superclass and subclass

    Super keyword

    Extends keyword Inheritance Hierarchy

    Method Overriding

    Protected access specifier

  • 7/28/2019 OOP Lecture 10

    4/22

    Example

    public class Box {

    double width;

    double height;

    double depth;

    Box() {

    }

    Box(double w, double h, double d)

    {

    width = w;

    height = h;

    depth = d;

    } void getVolume() {

    System.out.println("Volume is : " +

    width * height * depth);

    }

    }

    public class MatchBox extends Box {

    double weight;

    MatchBox() { }

    MatchBox(double w, double h, double d, double m)

    {

    super(w, h, d);

    weight = m;

    }

    public static void main(String args[])

    {

    MatchBox mb1 = new MatchBox(10, 10, 10, 10);

    mb1.getVolume();

    System.out.println("width of MatchBox 1 is " +

    mb1.width);

    System.out.println("height of MatchBox 1 is " +mb1.height);

    System.out.println("depth of MatchBox 1 is " +

    mb1.depth);

    System.out.println("weight of MatchBox 1 is " +

    mb1.weight);

    }

    }

  • 7/28/2019 OOP Lecture 10

    5/22

    What is not possible using

    java class Inheritance?

    1. Private members of the superclass are not inheritedby the subclass and can only be indirectly accessed.

    2. Members that have default accessibility in thesuperclass are also not inherited by subclasses inother packages, as these members are only accessibleby their simple names in subclasses within thesame package as the superclass.

    3. Since constructors and initializer blocks are not

    members of a class, they are not inherited by asubclass.

    4. A subclass can extend only one superclass

  • 7/28/2019 OOP Lecture 10

    6/22

    class Vehicle {

    int noOfTyres; // no of tyres

    private boolean accessories;

    String brand;

    private static int counter; Vehicle()

    {System.out.println("Constructor of the Super class called");

    noOfTyres = 5;

    accessories = true;

    brand = "X"; counter++; }

    public void switchOn() {accessories = true; } publicvoid switchOff() { accessories =false; }

    public boolean isPresent() {

    return accessories; } private void getBrand() {

    System.out.println("VehicleBrand: " + brand); } // Staticmethods

    public static voidgetNoOfVehicles() {System.out.println("Numberof Vehicles: " + counter); } }

  • 7/28/2019 OOP Lecture 10

    7/22

    Example

    class Car extends Vehicle {

    private int carNo = 10;

    public void printCarInfo() {System.out.println("Car number: " +carNo);

    System.out.println("No of Tyres: " +

    noOfTyres); // Inherited. // System.out.println("accessories: " +

    accessories); // Not Inherited.

    System.out.println("accessories: " +isPresent()); // Inherited. //

    System.out.println("Brand: " +getBrand()); // Not Inherited.System.out.println("Brand: " +brand); // Inherited. //

    System.out.println("Counter: " +counter); // Not Inherited.

    getNoOfVehicles(); // Inherited. } }

    public class VehicleDetails

    { // (3)

    public static void main(String[] args)

    { new Car().printCarInfo(); }

    }

  • 7/28/2019 OOP Lecture 10

    8/22

    This and super

    class Counter {

    int i = 0;

    Counter increment()

    { i++; return this; } void print()

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

    } }

    public class CounterDemo extends

    Counter

    { public static void main(String[] args)

    { Counter x = new Counter();

    x.increment().increment().increment(

    ).print(); }

    }

    The two keywords, this and super to help youexplicitly name the field or method that youwant.

    Using this and super you have full control onwhether to call a method or field present inthe same class or to call from the immediatesuperclass.

    This keyword is used as a reference to thecurrent object which is an instance of thecurrent class.

    The keyword super also references thecurrent object, but as an instance of thecurrent classs super class.

    The this reference to the current object isuseful in situations where a local variablehides, or shadows, a field with the same

    name. If a method needs to pass the currentobject to another method, it can do so usingthe this reference. Note that the thisreference cannot be used in a static context,as static code is not executed in the contextof any object.

  • 7/28/2019 OOP Lecture 10

    9/22

    public class ClassC extends ClassB {

    @Override

    public void print()

    {

    System.out.println("C");

    super.print();

    Object a=super.getClass();

    System.out.println(a);

    }

    }

    public class Main {

    public static void main (String[] args)

    {

    ClassC objc=new ClassC();

    objc.print();

    }

    }

    public class ClassB

    {

    public void print ()

    {

    System.out.println("B");

    }

    }

  • 7/28/2019 OOP Lecture 10

    10/22

    Method Overriding

    In a class hierarchy, when a method

    in a subclass has the same name and

    type signature as a method in its

    superclass, then the method in the

    subclass is said to override the

    method in the superclass. When an overridden method is called

    from within a subclass, it will always

    refer to the version of that method

    defined by the subclass. The version

    of the method defined by the

    superclass will be hidden. Considerthe following:// Method overriding.

    class A {int i, j;A(int a, int b) {i = a;j = b;}// display i and jvoid show() {System.out.println("i and j: " + i + " " + j);}}

    class B extends A {int k;B(int a, int b, int c) {super(a, b);k = c;}// display k this overrides show() in Avoid show() {

    System.out.println("k: " + k);} }

    class Override {public static void main(String args[]) {B subOb = new B(1, 2, 3);subOb.show(); // this calls show() in B}}

  • 7/28/2019 OOP Lecture 10

    11/22

    Abstract class

    An abstract class is a class that leaves one or more method implementations unspecified by

    declaring one or more methods abstract. An abstract method has no body (i.e., noimplementation).

    A subclass is required to override the abstract method and provide an implementation.

    Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class.

    abstract public class abstract-base-class-name {

    // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params );

    ... // other abstract methods, object methods, class methods

    }

    public class derived-class-name extends abstract-base-class-name {

    public return-type abstract-method-name (formal-params) { stmt-list; }

    ... // other method implementations }

    It would be an error to try to instantiate an object of an abstract type:

    abstract-class-name obj = new abstract-class-name(); // ERROR!

    That is, operator new is invalid when applied to an abstract class.

  • 7/28/2019 OOP Lecture 10

    12/22

    Example abstract class Point { private int x, y;

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

    y; }

    public void move(int dx, int dy)

    { x += dx; y += dy; plot(); }

    public abstract void plot(); // has no

    implementation

    }

    abstract class ColoredPoint extends Point {

    private int color;

    protected public ColoredPoint(int x, int y,

    int color)

    { super(x, y); this.color = color; }

    }

    class SimpleColoredPoint extends

    ColoredPoint {

    public SimpleColoredPoint(int x, int y, int

    color) { super(x,y,color); }

    public void plot() { ... } // code to plot a

    SimpleColoredPoint }

    Since ColoredPoint does not provide animplementation of the plot method, it must bedeclared abstract.

    The SimpleColoredPoint class does implement theinherited plot method. It would be an error to try toinstantiate a Point object or a ColoredPoint object.

    However, you can declare a Point reference andinitialize it with an instance of a subclass object thatimplements the plot method:

    Point p = new SimpleColoredPoint(a, b, red);p.plot();

  • 7/28/2019 OOP Lecture 10

    13/22

    Interface

    An abstract class with only static final instancevariables and

    All abstract methods is called an interface.

    think of an interface as an abstract class with allabstract methods.

    The interface itself can have either public, package,private or protected access defined.

    All methods declared in an interface are implicitlyabstract and implicitly public. It is not necessary,and in fact considered redundant to declare amethod in an interface to be abstract.

    You can define data in an interface, but it is lesscommon to do so. If there are data fieldsdefinedin

    an interface, then they are implicitly defined to be:

    public.

    static, and

    final In other words, any data defined in an interface

    are treated as public constants.

    Note that a class and an interface in the samepackage cannot share the same name.

    Mthods cannot be final ???

    Interface names and class names in the samepackage must be distinct.

    public interface interface-name {

    // if any data are defined, they must be constants

    public static final type-name var-name = constant-expr;

    // one or more implicitly abstract and public

    methods return-type method-name ( formal-params );

    }

  • 7/28/2019 OOP Lecture 10

    14/22

    When to use an Interface vs when to

    use an abstract class an abstract class can have a mix of abstract and non-abstract methods, so some default

    implementations can be defined in the abstract base class. An abstract class can also have static

    methods, static data, private and protected methods, etc. In other words, a class is a class, so it

    can contain features inherent to a class. The downside to an abstract base class, is that since their

    is only single inheritance in Java, you can only inherit from one class.

    an interface has a very restricted use, namely, to declare a set of public abstract method

    singatures that a subclass is required to implement. An interfaces defines a set of type

    constraints, in the form of type signatures, that impose a requirement on a subclass to implement

    the methods of the interface. Since you can inherit multiple interfaces, they are often a very

    useful mechanism to allow a class to have different behaviors in different situations of usage by

    implementing multiple interfaces.

    It is usually a good idea to implement an interface when you need to define methods that are to be

    explicitly overridden by some subclass. If you then want some of the methods implemented with

    default implementations that will be inherited by a subclass, then create an implementation class

    for the interface, and have other class inherit (extend) that class, or just use an abstract base class

    instead of an interface.

  • 7/28/2019 OOP Lecture 10

    15/22

    Example

    interface X {

    void f();

    int g();

    }

    class XImpl implements X {

    void g() { return -1; } // defaultimplementation for g()

    } class Y extends XImpl implements X {

    void f() { ... } // provide implementation forf()

    }

    Note that when you invoke an abtractmethod using a reference of the type of anabstract class or an

    interface, the method call is dynamicallydispatched.

    X x = new Y();

    x.f();

    The call x.f() causes a run-time determinationof the actual type of object that x refers to,then a

    method lookup to determine whichimplementation of f() to invoke. In this case,Y.f(x) is called, but

    the type of x is first converted to Y so thatthe this reference is initialized to areference of type Y

    inside of f(), since the implicit type signatureof Y.f() is really Y.f(final Y this);

  • 7/28/2019 OOP Lecture 10

    16/22

    Example

    public interface Working

    {

    public void work();

    }

    public class WorkingDogimplements Working

    {

    public WorkingDog(String nm)

    {

    ..

    }

    public void work()

    // this method specific to//WorkingDog

    {

    System.out.println("I can herdsheep and cows");

    }

    }

  • 7/28/2019 OOP Lecture 10

    17/22

    interface Shape { publicdouble area(); publicdouble volume(); }Belowis a Point class thatimplements the Shapeinterface.

    public class Pointimplements Shape { staticint x, y; public Point() { x =0; y = 0; } public doublearea() { return 0; } publicdouble volume() { return0; } public static voidprint() {System.out.println("point:" + x + "," + y); } publicstatic void main(Stringargs[]) { Point p = newPoint(); p.print(); } }

  • 7/28/2019 OOP Lecture 10

    18/22

    Polymorphism

    Method Overloading

    Method Overriding

    Polymorphism Example

    For example, given a base classshape,

    polymorphism enables theprogrammer to definedifferent area methods forany number of derived

    classes, such as circles,rectangles and triangles.

    No matter what shape anobject is, applying the

    area method to it will returnthe correct results.

  • 7/28/2019 OOP Lecture 10

    19/22

    3 Forms of Polymorphism

    in Java program

    Method overriding

    Methods of a subclass override the methods of a

    superclass

    Method overriding (implementation) of the abstract

    methods

    Methods of a subclass implement the abstract methods

    of an abstract class

    Method overriding (implementation) through the

    Java interface Methods of a concrete class implement the methods of

    the interface

  • 7/28/2019 OOP Lecture 10

    20/22

    Example

    public class Person {

    String name="Person";

    public String getName(){

    System.out.println("Employee Name:" + name);

    return name;

    }

    public static void printInformation( Person p ){

    // It will call getName() method of the

    // actual object instance that is passed

    p.getName();

    }

    }

    public class Student extends Person{

    String name="Student";

    @Override

    public String getName(){

    System.out.println("Student Name:" + name); return name;

    }

    }

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

    Student studentObject = new Student();

    Employee employeeObject = new Employee();

    Person ref = studentObject; // Person

    reference points // to a Student object

    // Calling getName() of the Student object

    instance

    String name = ref.getName();

    //printInformation(studentObject);

    }

    }

  • 7/28/2019 OOP Lecture 10

    21/22

    Object class

    The Objectclass is the highest superclass(ie. rootclass) of Java. All other classes aresubclasses (children or descendants) inherited

    from the Object class. The Object class includesmethods such as:

    clone()

    equals()

    copy(Object src) finalize() getClass() hashCode()

    notify() notifyAll() toString() wait()

  • 7/28/2019 OOP Lecture 10

    22/22