Вы находитесь на странице: 1из 22

Object-Oriented Programming Lecture 10

Dr. Zareen Fawad Department of Computer Science COMSATS Institute of Information Technology, Wah

Overview
Inheritance Abstract classes Interfaces Polymorphism Exception Handling

Inheritance
Superclass and subclass Super keyword Extends keyword Inheritance Hierarchy Method Overriding Protected access specifier

Example

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); } }

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); } }

What is not possible using java class Inheritance?


1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed. 2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass. 3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass. 4. A subclass can extend only one superclass

class Vehicle { int noOfTyres; // no of tyres private boolean accessories; String brand; private static int counter; Vehicle() { System.out.println("Construct or of the Super class called"); noOfTyres = 5; accessories = true; brand = "X"; counter++; }

public void switchOn() { accessories = true; } public void switchOff() { accessories = false; } public boolean isPresent() { return accessories; } private void getBrand() { System.out.println("Vehicle Brand: " + brand); } // Static methods public static void getNoOfVehicles() { System.out.println("Number of Vehicles: " + counter); } }

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(); } }

This and super


class Counter { int i = 0; Counter increment() { i++; return this; } void print() { System.out.println("i = " + i); }}
The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current classs super class. The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

public class CounterDemo extends Counter { public static void main(String[] args) { Counter x = new Counter(); x.increment().increment().increment( ).print(); } }

public class ClassB { public void print () { System.out.println("B"); } }

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(); } }

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. Consider the following:// Method overriding.
class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void 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 A void 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 }}

Abstract class
An abstract class is a class that leaves one or more method implementations unspecied by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). 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.

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 }

Example
Since ColoredPoint does not provide an implementation of the plot method, it must be declared abstract. The SimpleColoredPoint class does implement the inherited plot method. It would be an error to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point reference and initialize it with an instance of a subclass object that implements the plot method: Point p = new SimpleColoredPoint(a, b, red); p.plot();

Interface
An abstract class with only static nal instance variables and All abstract methods is called an interface. think of an interface as an abstract class with all abstract methods. The interface itself can have either public, package, private or protected access dened. All methods declared in an interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to declare a method in an interface to be abstract. You can dene data in an interface, but it is less common to do so. If there are data elds dened in an interface, then they are implicitly dened to be: public. static, and nal In other words, any data dened in an interface are treated as public constants. Note that a class and an interface in the same package cannot share the same name. Mthods cannot be final ??? Interface names and class names in the same package must be distinct. public interface interface-name { // if any data are defined, they must be constants public static final type-name var-name = constantexpr; // one or more implicitly abstract and public methods return-type method-name ( formal-params ); }

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 dened 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 denes 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 dene 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.

Example
interface X { void f(); int g(); } class XImpl implements X { void g() { return -1; } // default implementation for g() } class Y extends XImpl implements X { void f() { ... } // provide implementation for f() } Note that when you invoke an abtract method using a reference of the type of an abstract class or an interface, the method call is dynamically dispatched. X x = new Y(); x.f(); The call x.f() causes a run-time determination of the actual type of object that x refers to, then a method lookup to determine which implementation of f() to invoke. In this case, Y.f(x) is called, but the type of x is rst converted to Y so that the this reference is initialized to a reference of type Y inside of f(), since the implicit type signature of Y.f() is really Y.f(nal Y this);

Example
public interface Working { public void work(); } public class WorkingDog implements Working { public WorkingDog(String nm) { .. } public void work() // this method specific to //WorkingDog { System.out.println("I can herd sheep and cows"); } }

interface Shape { public double area(); public double volume(); }Below is a Point class that implements the Shape interface.

public class Point implements Shape { static int x, y; public Point() { x = 0; y = 0; } public double area() { return 0; } public double volume() { return 0; } public static void print() { System.out.println("point: " + x + "," + y); } public static void main(String args[]) { Point p = new Point(); p.print(); } }

Polymorphism
Method Overloading Method Overriding Polymorphism Example For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results.

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

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); } }

Object class
The Object class is the highest superclass (ie. root class) of Java. All other classes are subclasses (children or descendants) inherited from the Object class. The Object class includes methods such as: clone() equals() copy(Object src) finalize() getClass() hashCode() notify() notifyAll() toString() wait()