Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit-ii.

Similar presentations


Presentation on theme: "Unit-ii."— Presentation transcript:

1 Unit-ii

2 INHERITANCE BASICS Reusability is achieved by INHERITANCE
The process of inheriting the members of a class into another class is called inheritance. The class whose members are extended is known as super or base or parent class. The class which extends the members of super class is known as sub or derived or child class A class can either extends another class or can implement an interface.

3 What really happens? String name; Date dob; Date startDate;
class Person{ String name; Date dob; ….. } Person name = "John Smith" dob = Jan 13, 1954 Employee name = "Sally Halls" dob = Mar 15, 1968 employeeID = 37518 salary = 65000 startDate = Dec 15, 2000 is a kind of Employee{ int employeeID; double salary; Date startDate; ….. …. }

4 class B implements A { ….. } A interface B sub class
class B extends A { ….. } A super class B sub class B <<class>> A <<interface>> class B implements A { ….. } A interface B sub class B <<class>>

5 Various Forms of Inheritance
Single Inheritance Hierarchical Inheritance A A X X B B A B C A B C NOT SUPPORTED BY JAVA MultiLevel Inheritance Multiple Inheritance SUPPORTED BY JAVA A A A B A B B B C C C C

6 Forms of Inheritance WRONG WRONG
Mulitiple 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 { { OR } } A C D Z WRONG WRONG

7 Defining a Subclass Syntax :
class <subclass name> extends <superclass name> { variable declarations; method declarations; }

8 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.

9 void f1() { System.out.println( “Class A “) } } class B extends
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

10 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.

11 Using super to Call Superclass Constructors
no-parameter constructor automatically inserted by a compiler(default constructor). 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).

12 super(parameter-list);
Compiler inserts a default constructor only if you don’t define any constructor ( parameter / no-parameter) explicitly. super(..) is used to call super class constructor. super(parameter-list); parameter-list specifies any parameters needed by the constructor in the superclass.

13 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.

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

15 In Which Order Constructors Are executed
In a class hierarchy constructors are executed in the order of derivation, from superclass to subclass.

16 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 A’s constructor Inside B’s constructor Inside C’s constructor

17 A Second Use of super super.member
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.

18 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++; }

19 Using final with Inheritance
The keyword final has three uses. To create constant To prevent overriding To prevent inheritance

20 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.

21 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

22 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.

23 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.

24 Ex:- Area of a figure Rectangle Triangle double area()
double dim1,dim2; abstract double area(); Rectangle Triangle double area() { return dim1*dim2;} double area() { return dim1*dim2/2;}

25 abstract class Figure { double dim1; double dim2; Figure(double a, double b) dim1 = a; dim2 = b; } double area(); class Rectangle extends Figure Rectangle(double a, double b) super(a, b); // override area for rectangle double area() return dim1 * dim2;

26 class Triangle extends Figure { Triangle(double a, double b) super(a, b); } // override area for right triangle double area() return dim1 * dim2 / 2; class AbstractAreas public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8);

27 Figure figref; // this is OK, no object is created figref = r; System
Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); figref = t; } Output : Area is 45.0 Area is 40.0

28 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 )

29 Example person, student, Employee
String theName; String getInfo() Student Int theRegNum; String getInfo() Employee String dept; String getInfo()

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

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

32 public class Professor extends Person {
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();

33 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.

34 Largest element of n numbers using method overloading
class LargeDemo { public static void main( String arg[ ] ) int a[ ]={ 1,2,7,0,4 }; double d[ ]={ 2.4,5.6,7.2,1.5 } Large L=new Large(); int large=L.Large(a); System.out.println(large); double large=L.Large(d); } class Large { int largest( int x[ ] ) …. } int largest( double y[ ] )

35 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.

36 void f1() { System.out.println( “Class A “) } } class B extends {
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

37 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.

38 Import methods of Object class
Class getClass() Returns a Class object that represents this object’s class name. int hashCode() Every Java object has a hash code, which is an int representation of the object. boolean equals(Object obj) Indicates whether this object is equal to the obj object.

39 2. Generally toString and equals methods are overridden .
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 .

40 Ex: class Account { String Name; long acno; String type; double bal; String addr; Account() { Name=“smith” acno=123; type=“savings”; bal=5000; addr=“hyd”; } void deposit( double d) bal=bal+deposit;

41 void withdraw( double w) { if( bal>w) bal=bal-w; } public String toString() return Name+” “+ acno+” “+type+” “+ bal+” “+ addr; public boolean equals( Object a) Account a2=(Account)a; if( name==a2.name && acno==a2.acno && type==a2.type && bal==a2.bal&& addr==a2.addr) return true; else return false; }

42 class ExecuteAccount { public static void main( String arg[ ]) Account a1=new Account(); Account a2=new Account(); System.out.println(“Class Name=“+ a1.getClass() ); System.out.println(“hash Code of a1=“+ a1.hashCode() ); System.out.println(“hash Code of a2=“+ a2.hashCode() ); System.out.println(“toString of a1=“+ a1.toString() ); System.out.println(“toString of a2=“+ a2.toString() ); System.out.println(“Are objects same=“+ a1.equals(a2) ); } output

43 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.

44 Rapid Prototyping (quickly assemble from pre-existing components)
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.

45 Information Hiding Code Sharing ( within a project )
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.

46 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 )

47 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.

48 END

49 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 don’t 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.

50 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.

51 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 System.out.println("Inside Area for Rectangle."); return dim1 * dim2;

52 The output from the program is shown here: Inside Area for Rectangle.
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; figref = f; 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


Download ppt "Unit-ii."

Similar presentations


Ads by Google