java unit iii
TRANSCRIPT
-
8/3/2019 Java Unit III
1/59
Unit-iii
-
8/3/2019 Java Unit III
2/59
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 BreaksSound
Systems
:
:
:
:
:
:
-
8/3/2019 Java Unit III
3/59
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 uniquebehavior.
This abstraction allows people to use a car without worrying
the complexity of the parts that form the car.
-
8/3/2019 Java Unit III
4/59
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 childrenofObjectclass.
Objectclass provides minimum functionality thatis common to all the objects.
-
8/3/2019 Java Unit III
5/59
Import methods ofObjectclass
Class getClass() Returns a Class object thatrepresents this objects classname.
inthashCode() Every Java object has a hash code,which is an int representation ofthe object thats useful for certainoperations.
boolean equals(Objectobj) Indicates whether thisobject is equal to the objobject.
-
8/3/2019 Java Unit III
6/59
StringtoString() Returns a String representation of
this object. which is veryuseful for debugging.
Note :1. Override any of these methods to
provide your own information about an
object.
2. Generally toStringand equals methods
are overridden .
-
8/3/2019 Java Unit III
7/59
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.
-
8/3/2019 Java Unit III
8/59
Principle of Substitutability:
IfB is a subclass of A, instances of B canbe substitutedfor instances ofA in any
situation with noobservableeffect.
-
8/3/2019 Java Unit III
9/59
Subclass, Subtype
Subtype:
A child that satisfies principle of substitutability.
Subclass:
A child that is created using inheritance, it may or may not satisfythe 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.
-
8/3/2019 Java Unit III
10/59
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
-
8/3/2019 Java Unit III
11/59
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 hierarchicalinheritance
Hierarchical Inheritance
X
A B C
X
A B C
-
8/3/2019 Java Unit III
12/59
Example
person, student, Employee
Student
Int theRegNum:
String getInfo()
Person
String theName;
String getInfo()
Employee
String dept:
String getInfo()
-
8/3/2019 Java Unit III
13/59
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();
-
8/3/2019 Java Unit III
14/59
Subclasspublic 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();
-
8/3/2019 Java Unit III
15/59
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();
-
8/3/2019 Java Unit III
16/59
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
A B C
X
A B C
-
8/3/2019 Java Unit III
17/59
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;}
-
8/3/2019 Java Unit III
18/59
Extension
A child class only adds new behavior in the subclass anddoes not modify or alter anything inherited from parent.
This type of inheritance is called as single ormultilevel
inheritance.
A
B
Single Inheritance
A
B
MultiLevel Inheritance
A
B
C
A
B
C
-
8/3/2019 Java Unit III
19/59
Combination
Subclass class inherits features from more than oneParent.
This types of inheritance is called as multiple inheritance.
Java has single inheritance via subclassing (extends),
but multiple inheritance via interface implementations(implements).
A B
C
Multiple Inheritance
NOT SUPPORTED BY JAVA
A B
C
Multiple Inheritance
SUPPORTED BY JAVA
-
8/3/2019 Java Unit III
20/59
Multiple Inheritance can be implemented by
implementing multiple interfaces not by extendingmultiple classes.
Example :
class Z extends A implements C , D{ }
OK
class Z extends A ,B class Z extends A extends B
{ {
OR} }
A C D
Z
WRONG WRONG
-
8/3/2019 Java Unit III
21/59
Construction
A class can construct almost all of its desiredfunctionality from parent functionality by taking
its own method names and parameter lists.
Ex: In utilpackage the class, Stackis
constructed using inheritance from the
class Vector.
-
8/3/2019 Java Unit III
22/59
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
-
8/3/2019 Java Unit III
23/59
boolean isEmpty(); Returns true if the vector is empty otherwise false.
int size() Returns the number of elements currently in the vector.
-
8/3/2019 Java Unit III
24/59
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; }
}
}
-
8/3/2019 Java Unit III
25/59
Limitation
It occurs when the behavior of subclass is smaller ormore 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.
-
8/3/2019 Java Unit III
26/59
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.
-
8/3/2019 Java Unit III
27/59
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 pre-
existing components) Software systems can be generated more quickly and easily by
assembling preexisting components. This type of development is called Rapid Prototyping.
-
8/3/2019 Java Unit III
28/59
Information Hiding
The programmer who reuses a software componentneeds only to understand the nature of thecomponent and its interface.
He does not have to know the techniques used toimplement 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 willcontribute only once to the size of the resultingprogram.
-
8/3/2019 Java Unit III
29/59
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 low-
level parts.
Ex: AWT ( Abstract Window Toolkit )
-
8/3/2019 Java Unit III
30/59
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.
-
8/3/2019 Java Unit III
31/59
Inheritance Basics
The key word extends is used to define inheritance in
Java.
Syntax:-
class subclass-nameextends superclass-name{// body of class
}
-
8/3/2019 Java Unit III
32/59
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.
-
8/3/2019 Java Unit III
33/59
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
}
}
-
8/3/2019 Java Unit III
34/59
superuses
superhas two uses.
To call superclass constructor.
To access a member of the superclass that is hidden
by a member of a subclass.
-
8/3/2019 Java Unit III
35/59
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 fornumeric types, null for object references and
characters, and false for booleans).
-
8/3/2019 Java Unit III
36/59
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-listspecifies any parameters needed by
the constructor in the superclass.
-
8/3/2019 Java Unit III
37/59
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.
-
8/3/2019 Java Unit III
38/59
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);
}
}
-
8/3/2019 Java Unit III
39/59
In Which Order Constructors Are Called
In a class hierarchy constructors are called in the orderof derivation, from superclass to subclass.
-
8/3/2019 Java Unit III
40/59
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
-
8/3/2019 Java Unit III
41/59
A Second Use of super
The second form ofsuperacts somewhat like this, except that it
always refers to the superclass of the subclass in which it is used.
general form:
super.member
Here, membercan be either a methodor an instancevariable.
This form is used to resolve name collisions that might occurbetween superand subclass member names.
-
8/3/2019 Java Unit III
42/59
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() ) ; // f1() in A}
void f1() { i++; }
}
-
8/3/2019 Java Unit III
43/59
Using final with Inheritance
The keyword finalhas three uses. To create constant
To prevent overriding
To prevent inheritance
-
8/3/2019 Java Unit III
44/59
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.
-
8/3/2019 Java Unit III
45/59
Using final to Prevent Inheritance
Classes declared as final cannot be inherited.
It is illegal to declare a class as both abstract and final, becausean abstract class is incomplete by itself and depends upon itssubclasses to provide complete implementations.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
-
8/3/2019 Java Unit III
46/59
Abstract Classes
Am
ethodthat has been declared but not defined is an abstractmethod.
Any class that contains at least one abstract method is an abstractclass.
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.
-
8/3/2019 Java Unit III
47/59
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 notdefine all the inherited
abstract methods, it is also an abstract class.
-
8/3/2019 Java Unit III
48/59
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();
}
}
-
8/3/2019 Java Unit III
49/59
Method Overriding
When a method in a subclass has the same
name
signature and
return typeas a method in its superclass, then the method in the subclass is
said to be overriden.
Take person student employee example( Diagram and code )
-
8/3/2019 Java Unit III
50/59
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.
-
8/3/2019 Java Unit III
51/59
Maximum element of n numbers using method
overloading
-
8/3/2019 Java Unit III
52/59
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which acall to an overridden method is resolved at run time,
rather than at compile time.
When an overridden method is called through asuperclass 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.
-
8/3/2019 Java Unit III
53/59
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
-
8/3/2019 Java Unit III
54/59
Important questions
1.a) Explain about final classes, final methods and finalvariables?
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 whathappens. Finally, override it in all the derived classes,
Explain in detail about each situation.
-
8/3/2019 Java Unit III
55/59
3. Create a base class with an abstract print( ) method that
is overridden in a derived class. The overridden versionof 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.
-
8/3/2019 Java Unit III
56/59
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 forRectangle.");return dim1 * dim2;
}
}
-
8/3/2019 Java Unit III
57/59
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 forRectangle.
Area is 45Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
-
8/3/2019 Java Unit III
58/59
Differences between methods andconstructors. There is noreturn 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 noreturn statement in the body of the
constructor.
The firstline of a constructor must either be a call onanother constructor in the same class (using this), ora call on the superclass constructor (using super). Ifthe first line is neither of these, the compilerautomatically inserts a call to the parameterless superclass constructor.
-
8/3/2019 Java Unit III
59/59
When you create a new instance (a new object) of a class using the new keyword, aconstructorfor that class is called. Constructors are used to initialize the instancevariables (fields) of an object. Constructors are similar to methods, but with someimportant differences.
Constructorname 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 defaultconstructor calls the default parent constructor (super()) and initializes all instancevariables to default value (zero for numeric types, null for object references, and falsefor booleans).
Default constructor is created only if there are no constructors. If you define anyconstructor for your class, no default constructor is automatically created.
These differences in syntax between a constructor and method are sometimes hardto see when looking at the source. It would have been better to have had a keywordto clearly mark constructors as some languages do.
this(...) - Calls anotherconstructor in same class. Often a constructor with fewparameters will call a constructor with more parameters, giving default values for themissing parameters. Use this tocallotherconstructors in the same class.
super(...). Use superto call a constructor in a parent class. Calling the constructor forthe superclass must be the firststatement in the body of a constructor. If you are
satisfied with the default constructor in the superclass, there is no need to make a callto it because it will be supplied automatically.