Download Unit –III - Vitaecse

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Unit –III
(Inheritance – Hierarchical abstractions, Base class object, subclass, subtype, substitutability,
forms of inheritance- specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using
final with inheritance, polymorphism- method overriding, abstract classes and object classes.)
Hierarchical Abstraction
An essential element of object-oriented programming is abstraction.
Humans manage complexity through abstraction. For example, people do not think of a car as a
set of tens of 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 being overwhelmed by the complexity of the
parts that form the car. They can ignore the details of how the engine, transmission, and braking
systems work.
Instead they are free to utilize the object as a whole.
Class Hierarchy
A child class of one parent can be the parent of another child, forming class hierarchies
At the top of the hierarchy there’s a default class called Object
 Good class design puts all common features as high in the hierarchy as reasonable
 The class hierarchy determines how methods are executed
 inheritance is transitive
 An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an
instance of class Object
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 defined in Java, is a child of Object class, which provides minimal
functionality guaranteed to e common to all objects.
 Methods defined in Object class are;
1.
2.
3.
4.
o equals(Object obj) Determine whether the argument object
is the same as
the receiver.
o getClass() Returns the class of the receiver, an object of type Class.
o hashCode() Returns a hash value for this object. Should be overridden when the
equals method is changed.
o toString() Converts object into a string value. This method is also often
overridden.
a class obtains variables and methods from another class
the former is called subclass, the latter super-class (Base class)
a sub-class provides a specialized behavior with respect to its super-class
inheritance facilitates code reuse and avoids duplication of data.
 One of the pillars of object-orientation.
 A new class is derived from an existing class:
o existing class is called super-class
o derived class is called sub-class
 A sub-class is a specialized version of its super-class:
1) has all non-private members of its super-class
2) may provide its own implementation of super-class methods
o Objects of a sub-class are a special kind of objects of a super-class.
extends
 It Is a keyword used to inherit a class from another class
 Allows to extend from only one class
class One
{
int a=5;
}
class Two extends One
{
int b=10;
}




One baseobj;// base class object.
super class object baseobj can be used to refer its sub class objects.
For example, Two subobj=new Two();
Baseobj=subobj // now its pointing to sub class
Subclass, Subtype and Substitutability
 A subtype is a class that satisfies the principle of substitutability.
 A subclass is something constructed using inheritance, whether or not it satisfies the
principle of substitutability.
 The two concepts are independent. Not all subclasses are subtypes, and (at least in some
languages) you can construct subtypes that are not subclasses.
 Substitutability is fundamental to many of the powerful software development techniques
in OOP.
 The idea is that, declared a variable in one type may hold the value of different type.
 Substitutability can occur through use of inheritance, whether using extends, or using
implements keywords.
 When new classes are constructed using inheritance, the argument used to justify the
validity of substitutability is as follows;
• Instances of the subclass must possess all data fields associated with its parent
class.
• Instances of the subclass must implement, through inheritance at least, all
functionality defined for parent class. (Defining new methods is not important for
the argument.)
• Thus, an instance of a child class can mimic the behavior of the parent class and
should be indistinguishable from an instance of parent class if substituted in a
similar situation.
•
•
•
The term subtype is used to describe the relationship between types that explicitly
recognizes the principle of substitution. A type B is considered to be a subtype of
A if an instances of B can legally be assigned to a variable declared as of type A.
The term subclass refers to inheritance mechanism made by extends keyword.
Not all subclasses are subtypes. Subtypes can also be formed using interface,
linking types that have no inheritance relationship.
Subclass:Methods allows to reuse a sequence of statements
Inheritance allows to reuse classes by deriving a new class from an existing one
The existing class is called the parent class, or superclass, or base class
The derived class is called the child class or subclass.
As the name implies, the child inherits characteristics of the parent(i.e the child
class inherits the methods and data defined for the parent class
Subtype
 Inheritance relationships are often shown graphically in a class diagram, with the arrow
pointing to the parent class
Substitutability (Deriving Subclasses)
In Java, we use the reserved word extends to establish an inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}
class Bird extends Animal
{
// class contents
public void fly() {…};
}
Defining Methods in the Child Class: Overriding by Replacement
A child class can override the definition of an inherited method in favor of its own that is, a
child can redefine a method that it inherits from its parent the new method must have the
same signature as the parent's method, but can have different code in the body. In java, all
methods except of constructors override the methods of their ancestor class by replacement.
E.g.: the Animal class has method eat()the Bird class has method eat() and Bird extends
Animal variable b is of class Bird, i.e. Bird b = …b.eat() simply invokes the eat() method of
the Bird class
If a method is declared with the final modifier, it cannot be overridden.
class A
{
void show()
{
System.out.println("Hello This is show() in A");
}// End of show() Method
} // End of class A
class B extends A
{
void show()
{
System.out.println("Hello This is show() in B");
}// End of show() Method
} // End of class B
class override
{
public static void main(String args[])
{
// super class reference variable
// can point to sub class object
A a1 = new A();
a1.show();
a1 = new B();
a1.show();
}
}
Forms of Inheritance
 These are 3 types:
1) Single Inheritance
A
B
A is the Super class and B is the sub class of A
2) Hierarchical Inheritance
A
B
C
A is the Super class and B,C,D are the sub classes of A
3) Multi-level Inheritance
A
B
C
A is the super class of B and B is the super class of C
Declaring a Sub class:- Syntax :
class <subclass name> extends <superclass name>
{
variable declarations;
method declarations;
D
•
•
}
Extends keyword signifies that properties of the super class are extended to sub class
Sub class will not inherit private members of super class
Member access rules
 Visibility modifiers determine which class members are accessible and which do not
 Members (variables and methods) declared with public visibility are accessible, and those
with private visibility are not
 Problem: How to make class/instance variables visible only to its subclasses?
Solution: Java provides a third visibility modifier that helps in inheritance situations: protected
Modifiers and Inheritance
Visibility Modifiers for class/interface:
public : can be accessed from outside the class definition.
protected : can be accessed only within the class definition in which it appears, within other
classess in the same package, or within the definition of subclassess.
private : can be accessed only within the class definition in which it appears.
default-access (if omitted) features accessible from inside the current Java package
Access Modifiers
Access Location
public
protected
default
private
Same Class
Yes
Yes
Yes
Yes
sub classes in same
package
Yes
Yes
Yes
No
Other Classes in
Same package
Yes
No
Yes
No
Subclasses in other
packages
Yes
Yes
No
No
Non-subclasses in
other packages
Yes
No
No
No
Use of “super” Keyword:
• Can be used to call super class constrctor
super();
super(<parameter-list>);
• Can refer to super class instance variables/Methods
super.<super class instance variable/Method>
1. Whenever a sub class object is created ,super class constructor is called first.
2. If super class constructor does not have any constructor of its own OR has an default
constructor then it is automatically called by Java Run Time by using call super()
3. If a super class has a parameterized constructor then it is the responsibility of the sub
class constructor to call the super class constructor by call
super(<parameters required by super class>)
4. Call to super class constructor must be the first statement in sub class constructor
The protected Modifier
 The protected visibility modifier allows a member of a base class to be accessed in the
child
 protected visibility provides more encapsulation than public does
 protected visibility is not as tightly encapsulated as private visibility
Example: Super-Class
class A {
int i;
void showi() {
System.out.println("i: " + i);
}
}
The Benefits of Inheritance
 Software Reusability (among projects)
 Increased Reliability (resulting from reuse and sharing of well-tested code)
 Code Sharing (within a project)
 Consistency of Interface (among related objects)
 Software Components
 Rapid Prototyping (quickly assemble from pre-existing components)
 Polymorphism and Frameworks (high-level reusable components)
Information Hiding.
The Costs of Inheritance
 Execution Speed
 Program Size
 Message-Passing Overhead
 Program Complexity (in overuse of inheritance)
 Acquiring the properties of an existing Object into newly creating Object to overcome the
redeclaration of properties in deferent classes.
Final Keyword:All methods and variables can be overridden by default in subclasses. This can be
prevented by declaring them as final using the keyword “final” as a modifier. For
example:
 final int marks = 100;
 final void display();
This ensures that functionality defined in this method cannot be altered any. Similarly,
the value of a final variable cannot be altered.
We can prevent an inheritance of classes by other classes by declaring them as final
classes.This is achieved in Java by using the keyword final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}
Any attempt to inherit these classes will cause an error.
Abstract Classes: When a class contains one or more abstract methods, it should be declared as abstract
class.
 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.
abstract class ClassName
{
...
…
abstract Type MethodName1();
…
…
Type Method2()
{
// method body
}
}
Shape is a abstract class.
public Circle extends Shape {
protected double r;
protected static final double PI =3.1415926535;
public Circle() { r = 1.0; )
public double area() { return PI * r * r; }
…
}
public Rectangle extends Shape {
protected double w, h;
public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }
}
Abstract Class Properties: A class with one or more abstract methods is automatically abstract and it cannot be
instantiated.
 A class declared abstract, even with no abstract methods can not be instantiated.
 A subclass of an abstract class can be instantiated if it overrides all abstract methods by
implementation them.
 A subclass that does not implement all of the super class abstract methods is itself
abstract; and it cannot be instantiated.
FAQs
1. Create an abstract class with no methods. Derive a class and add a method. Create a static
method that takes a reference to the base class, downcasts it to the derived class, and calls the
method. In main( ), demonstrate that it works. Now put the abstract declaration for the method in
the base class, thus eliminating the need for the downcast.
2. Is there any alternative solution for Inheritance. If so explain the advantages and disadvantages
of it.
3. Explain about Object class in detail.
4. Create an inheritance hierarchy of Rodent: Mouse, Gerbil, Hamster, etc. In the base class,
provide methods that are common to all Rodents, and override these in the derived classes to
perform different behaviors depending on the specific type of Rodent. Create an array of Rodent,
fill it with different specific types of Rodents, and call your base-class methods. Explain the
output.
5. What are the types of inheritances in java? Explain each of them in detail.
6 (a) Explain about Method Overriding in Java
(b) Write a java program to implement Method Over riding.
7. (a) Define multiple inheritance. Does Java Support multiple inheritance. Justify your answer.
(b) Write java program to implement the multilevel Inheritance.