Vous êtes sur la page 1sur 59

Unit-iii

Hierarchical Abstractions
 The process of arranging the system into layers by breaking them into pieces is called Hierarchical abstractions.  For example.,
 From the outside, the car is a single object.  Inside the car consists of several subsystems:  steering  brakes  sound system, and so on
Car Steering Breaks
Sound Systems

: :

: :

: :

 We manage the complexity through abstraction.  For example,


 People do not think of a car as a thousands of individual parts.  They think of it as a well-defined object with its own unique behavior.  This abstraction allows people to use a car without worrying the complexity of the parts that form the car.

Base Class Object


In Java, all classes use inheritance. If no parent class is specified explicitly, the base class Object is implicitly inherited. All classes( parent ) defined in Java, are children of Object class. Object class provides minimum functionality that is common to all the objects.

Import methods of Object class


Class getClass() Returns a Class object that represents this objects class name. Every Java object has a hash code, which is an int representation of the object thats useful for certain operations. Indicates whether this object is equal to the obj object.

int hashCode()

boolean equals(Object obj)

String toString()

Returns a String representation of this object. which is very

useful for debugging.

Note :1. Override any of these methods to provide your own information about an object. 2. Generally toString and equals methods are overridden .

Substitutability
The idea of substitutability is that, a variable declared in one type may hold the value of different type. Substitutability can occur through the use of inheritance, whether using extends, or using implements keywords.

Principle of Substitutability: If B is a subclass of A, instances of B can be substituted for instances of A in any situation with no observable effect.

Subclass, Subtype
Subtype:  A child that satisfies principle of substitutability. Subclass:  A child that is created using inheritance, it may or may not satisfy the principle of substitutability.

Note :  All subtypes are not subclasses and all subclasses are not subtypes. In java
 All subclasses are subtypes and all subtypes are subclasses.

Forms of Inheritance
 Inheritance can be used in a variety of ways.  The following are the most common forms of inheritance       Specialization Specification Extension Combination Limitation Construction

Specialization
 No new methods in the subclass.  The subclass overrides one or more methods, in order to specialize the class in some way.  This type of inheritance is called as hierarchical inheritance
Hierarchical Inheritance

Example
person, student, Employee
Person String theName; String getInfo()

Student Int theRegNum: String getInfo()

Employee String dept: String getInfo()

Superclass
public class Person { protected String Name; public Person(String name) { Name = name; } public String getInfo() { return Name; } } // Person Person girl = new Person (Sue); String stra = girl.getInfo();

Subclass
public class Student extends Person { private int theRegNum; public Student(String name, int reg) { super(name); theRegNum = reg; } // constructor public String getInfo() { return super.getName() + , + theRegNum; } } Student woman = new Student (Mary, 2000153); String stra = woman.getInfo();

public class Professor extends Person { private Strng dept; public Student(String name, String dep) { super(name); dept = dep; } // constructor public String getInfo() { return super.getName() + , + dept; } } Student woman = new Student (sue, CSE); String stra = woman.getInfo();

Specification
 No new methods in the subclass.  The child implements methods specified, but not implemented, in the parent.  abstract / interface keyword is used to specify the methods in the super class / interface.  This type of inheritance is also called as hierarchical inheritance.
X X

Ex:- Area of a figure


Figure double dim1,dim2; abstract double area()

Rectangle double area() { return dim1*dim2;}

Triangle double area() { return dim1*dim2/2;}

Extension
 A child class only adds new behavior in the subclass and does not modify or alter anything inherited from parent.  This type of inheritance is called as single or multilevel inheritance.
Single Inheritance MultiLevel Inheritance A A A B B B C C B A

Combination
 Subclass class inherits features from more than one Parent.  This types of inheritance is called as multiple inheritance.  Java has single inheritance via subclassing (extends), but multiple inheritance via interface implementations (implements).
Multiple Inheritance A
NOT SUPPORTED BY JAVA

Multiple Inheritance A B
SUPPORTED BY JAVA

 Multiple Inheritance can be implemented by implementing multiple interfaces not by extending multiple classes. Example :
class Z extends A implements C , D { }

OK
class Z extends A ,B { class Z extends A extends B {

WRONG
}

OR
}

WRONG

Construction
A class can construct almost all of its desired functionality from parent functionality by taking its own method names and parameter lists.

Ex: In util package the class, Stack is constructed using inheritance from the class Vector.

Vector class is a dynamic array. Some of the important methods of Vector class are

void addElement( Object element )


Specified element is added to the Vector

Object elementAt(int index)


returns the element at the location specified by index.

void removeElementAt(int index )


Removes the element at the location specified by index

boolean isEmpty();
Returns true if the vector is empty otherwise false.

int size()
Returns the number of elements currently in the vector.

Ex :
class stack extends Vector { public void push(Object i) { addElement(i); }

Object pop() { if( !isEmpty() ) { Object e=elementAt( size()-1 ); removeElementAt( size()-1 ); return e; } else{ System.out.println( " underflow "); return null; }

} }

Limitation
 It occurs when the behavior of subclass is smaller or more restrictive than the behavior of its parent class.  We can do this by overriding undesired methods, such that if they are executed they produce error messages, or print a message indicating they should not be used.  Example: Queue extends DoubleEndedQueue  Override frontInsert() and rearDelete() to display error messages.

The Benefits of Inheritance


Software Reusability ( among projects )
Many programmers spend much of their time rewriting code they have written many times before. Ex : code to insert a new element into a table can be written once and reused.

Increased Reliability
When the same components are used in two or more applications, the bugs can be discovered more quickly.

Software Components
Inheritance enables programmers to construct reusable components. The goal is to permit the development of new applications that require little or no actual coding. The java library offers a rich collection of software components for use in the development of applications.

Rapid Prototyping (quickly assemble from preexisting components)


Software systems can be generated more quickly and easily by assembling preexisting components. This type of development is called Rapid Prototyping.

Information Hiding
The programmer who reuses a software component needs only to understand the nature of the component and its interface. He does not have to know the techniques used to implement the component.

Code Sharing ( within a project )


It occurs when two or more classes inherit from a parent class. This code needs to be written only once and will contribute only once to the size of the resulting program.

Polymorphism (high-level reusable components)


Normally, code reuse decreases as one moves up to the high level components. Lowest-level components may be used in several different projects, but higher-level components are fixed to a particular application. Polymorphism in programming languages permits the programmer to generate high-level reusable components that can be modified to fit different applications by changing their lowlevel parts. Ex: AWT ( Abstract Window Toolkit )

The Costs of Inheritance


Execution Speed
Inherited methods, which we use in subclasses, are often run slowly than specialized code.

Program Size
The use of any software library increases program size.

Message-Passing Overhead
Message passing is more costly than invoking procedures.

Program Complexity
Overuse of inheritance often increases program complexity.

Inheritance Basics
 The key word extends is used to define inheritance in Java.
Syntax:class subclass-name extends superclass-name { // body of class }

 A subclass inherits all the members of its superclass except private members and constructors.  A Subclass instance can be assigned to Superclass class variable.  The type of the reference variable determines what members can be accessed, not the type of the object.  That is, whenever a subclass object is assigned to a superclass variable, you will have access only to those parts of the object defined by the superclass.

Ex:-

class A { int x=10; void f1() { System.out.println( Class A ) } } class B extends { int y=20; void f2() { System.out.println( Subclass B ); } } class RefDemo { public static void main( String args[ ] ) { A a1; a1=new B(); System.out.println( a1. y ); // wrong a1.f2(); // wrong } }

super uses
super has two uses.  To call superclass constructor.  To access a member of the superclass that is hidden by a member of a subclass.

Using super to Call Superclass Constructors Default constructor.


A parameterless constructor is a default constructor.
Automatically inserted by a compiler. Programmer can provide explicitly. Default constructor( created by a compiler ) initializes all instance variables to default values (zero for numeric types, null for object references and characters, and false for booleans).

Compiler inserts a default constructor only if you dont define any constructor ( parameter / parameterless) explicitly. super(..) is used to call super class constructor.

super(parameter-list);
 parameter-list specifies any parameters needed by the constructor in the superclass.

Compiler automatically inserts default form of super ( super () ) in each constructor. Compiler does not insert default form of super if you define super explicitly.  super( ) must be the first statement executed inside a subclass constructor.

class A { int x; A ( int a ) { x=a; } void f1() { System.out.println( Class A ) } } class B extends A { int y; B( int m, int n) { super( m); y= n ; } void f1() { System.out.println( Subclass B ); } } class RefDemo { public static void main( String args[ ] ) { B b1=new B(10, 20);

In Which Order Constructors Are Called


 In a class hierarchy constructors are called in the order of derivation, from superclass to subclass.

class A { A() { System.out.println("Inside A's constructor."); } } class B extends A { B() { System.out.println("Inside B's constructor."); } } class C extends B { C() { System.out.println("Inside C's constructor."); } } class CallingCons { public static void main(String args[]) { C c = new C(); } } The output from this program is shown here: Inside As constructor Inside Bs constructor Inside Cs constructor

A Second Use of super


 The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. general form:

super.member
 Here, member can be either a method or an instance variable.  This form is used to resolve name collisions that might occur between super and subclass member names.

Ex:class A { int i; void f1() { i++; } class B extends A { int i; // B i hides A i B(int a, int b) { super.i = a; // i in A i = b; // i in B System.out.println( super.f1() } void f1() { i++; } } }

) ; // f1() in A

Using final with Inheritance


The keyword final has three uses.
 To create constant  To prevent overriding  To prevent inheritance

Using final to Prevent Overriding


 Methods declared as final cannot be overridden.
class A { final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() { System.out.println( final method is overridden "); } // ERROR! Can't override.

Using final to Prevent Inheritance


 Classes declared as final cannot be inherited.  It is illegal to declare a class as both abstract and final, because an abstract class is incomplete by itself and depends upon its subclasses to provide complete implementations. final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... }

Abstract Classes
 A method that has been declared but not defined is an abstract method.  Any class that contains at least one abstract method is an abstract class.  You must declare the abstract method with the keyword abstract:
 abstract type name(parameter-list);

 You must declare the class with the keyword abstract:  abstract class MyClass {...}  An abstract class is incomplete  It has missing method bodies  You cannot instantiate (create a new instance of) an abstract class.

Contd..
 You can extend (subclass) an abstract class.
 If the subclass defines all the inherited abstract methods, it is complete and can be instantiated.  If the subclass does not define all the inherited abstract methods, it is also an abstract class.

Ex:abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[ ]) { B b = new B(); b.callme(); b.callmetoo(); } }

Method Overriding
 When a method in a subclass has the same
 name  signature and  return type
as a method in its superclass, then the method in the subclass is said to be overriden.

 Take person student employee example ( Diagram and code )

Polymorphism
 Polymorphism:  Assigning multiple meanings to the same method name.  Method to be executed is determined at execution time, not at compile time.  This process is called late binding or dynamic binding (run-time binding):  Ex : Method overloading.

Maximum element of n numbers using method overloading

Dynamic Method Dispatch


 Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than at compile time.  When an overridden method is called through a superclass reference, the method to execute will be based upon the type of the object created at the time the call occurs. Not the type of the reference variable.

Ex:-

class A { int x=10; void f1() { System.out.println( Class A ) } } class B extends { int x=20; void f1() { System.out.println( Subclass B ); } } class RefDemo { public static void main( String args[ ] ) { A a1; a1=new B(); a1.f1(); } } System.out.print( a1.x )

Output : Subclass B 10

Important questions
1.a) Explain about final classes, final methods and final variables? b) Explain about the abstract class with example program? 2. Add a new method in the base class of Shapes.java that prints a message, but dont override it in the derived classes. Explain what happens. Now override it in one of the derived classes but not the others, and Explain what happens. Finally, override it in all the derived classes, Explain in detail about each situation.

3. Create a base class with an abstract print( ) method that is overridden in a derived class. The overridden version of the method prints the value of an int variable defined in the derived class. At the point of definition of this variable, give it a nonzero value. In the base-class constructor, call this method. In main( ), create an object of the derived type, and then call its print( ) method. Explain the results. 4. Explain about Object class in detail.

Problem 2 solution:
class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } }

class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class Shapes { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } }

The output from the program is shown here: Inside Area for Rectangle. Area is 45 Inside Area for Triangle. Area is 40 Area for Figure is undefined. Area is 0

Differences between methods and constructors.


There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value. There is no return statement in the body of the constructor. The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.

When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences. Constructor name is class name. A constructors must have the same name as the class its in. Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans). Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created. These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do. this(...) - Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class. super(...). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

Vous aimerez peut-être aussi