Inheritance Inheritance is a fundamental Object Oriented concept

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Department of computer science N. Harika. Inheritance Inheritance is a fundamental Object Oriented concept A class can be defined as a "subclass" of another.
Inheritance The objectives of this chapter are: To explore the concept and implications of inheritance Polymorphism To define the syntax of inheritance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
Chapter 10 Classes Continued
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Chapter 10: Inheritance 1. Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
Java Inheritance in Java. Inheritance Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
BY:- TOPS Technologies
Inheritance. Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object Inheritance represents the IS-A.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind.
Final and Abstract Classes
Inheritance and Polymorphism
Inheritance in Java.
INHERITANCE IN JAVA.
Week 8 Lecture -3 Inheritance and Polymorphism
OOP’S Concepts in C#.Net
Interface.
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Interfaces.
Advanced Programming Behnam Hatami Fall 2017.
Advanced Java Programming
Sampath Kumar S Assistant Professor, SECE
METHOD OVERRIDING in JAVA
CS18000: Problem Solving and Object-Oriented Programming
Java – Inheritance.
Java Programming, Second Edition
Chapter 9 Carrano Chapter 10 Small Java
Chapter 14 Abstract Classes and Interfaces
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
Presentation transcript:

Inheritance Inheritance is a fundamental Object Oriented concept A class can be defined as a "subclass" of another class. The subclass inherits all data attributes of its superclass The subclass inherits all methods of its superclass The subclass can: Add new functionality Use inherited functionality Override inherited functionality superclass: Person - name: String - dob: Date subclass: Employee - employeeID: int - salary: int - startDate: Date

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

What really happens? In this example, we can say that an Employee "is a kind of" Person. An Employee object inherits all of the attributes, methods and associations of Person Person name = "John Smith" dob = Jan 13, 1954 Person - name: String - dob: Date Employee name = "Sally Halls" dob = Mar 15, 1968 employeeID = 37518 salary = 65000 startDate = Dec 15, 2000 is a kind of Employee - employeeID: int - salary: int - startDate: Date

Inheritance in Java Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object public class Person { private String name; private Date dob; [...] Person - name: String - dob: Date public class Employee extends Person { private int employeID; private int salary; private Date startDate; [...] Employee - employeeID: int - salary: int - startDate: Date Employee anEmployee = new Employee();

Types of Inheritance

Why Java doesn’t support multiple inheritance? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

Inheritance Hierarchy Each Java class has one (and only one) superclass. C++ allows for multiple inheritance Inheritance creates a class hierarchy Classes higher in the hierarchy are more general and more abstract Classes lower in the hierarchy are more specific and concrete Class There is no limit to the number of subclasses a class can have There is no limit to the depth of the class tree. Class Class Class Class Class Class Class

The class called Object At the very top of the inheritance tree is a class called Object All Java classes inherit from Object. The Object class is defined in the java.lang package Examine it in the Java API Specification Object

Constructors and Initialization Classes use constructors to initialize instance variables When a subclass object is created, its constructor is called. It is the responsibility of the subclass constructor to invoke the appropriate superclass constructors so that the instance variables defined in the superclass are properly initialized Superclass constructors can be called using the "super" keyword in a manner similar to "this" It must be the first line of code in the constructor If a call to super is not made, the system will automatically attempt to invoke the no-argument constructor of the superclass.

Object References and Inheritance A superclass reference can refer to an instance of the superclass OR an instance of ANY class which inherits from the superclass. BankAccount anAccount = new BankAccount(123456, "Craig"); BankAccount account1 = new OverdraftAccount(3323, "John", 1000.0); BankAccount name = "Craig" accountNumber = 123456 anAccount OverdraftAccount name = "John" accountNumber = 3323 limit = 1000.0 account1

super keyword The super keyword in java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of java super Keyword super can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor.

Referring immediate parent class instance variable. We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. class Animal{   String color=“green";   }   class Dog extends Animal{   String color="black";   void printColor(){   System.out.println(color); //prints color of Dog class   System.out.println(super.color); //prints color of Animal class   class TestSuper1{   public static void main(String args[]){   Dog d=new Dog();   d.printColor();   }}   Output: black green

super can be used to invoke parent class method class Animal{   void eat(){System.out.println("eating Animal");}   }   class Dog extends Animal{   void eat(){System.out.println("eating bread");}   void bark(){System.out.println("barking");}   void work(){   super.eat();   bark();   class TestSuper2{   public static void main(String args[]){   Dog d=new Dog();   d.work();   }}   Output: eating Animal barking

invoke parent class constructor class Animal{   Animal(){System.out.println("animal is created");}   }   class Dog extends Animal{   Dog(){   super();   System.out.println("dog is created");   class TestSuper3{   public static void main(String args[]){   Dog d=new Dog();   }}   Output: animal is created dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super() As we know well that default constructor is provided by compiler automatically if there is no constructor. But, it also adds super() as the first statement.

Final Methods and Final Classes Methods can be qualified with the final modifier Final methods cannot be overridden. This can be useful for security purposes. public final boolean validatePassword(String username, String Password) { [...] Classes can be qualified with the final modifier The class cannot be extended This can be used to improve performance. Because there an be no subclasses, there will be no polymorphic overhead at runtime. public final class Color { [...]

Interface An interface in java is a blueprint of a class. Interfaces specify what a class must do and not how.  It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. An interface is similar to a class in the following ways − An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file.

Interface is different from class ---- We cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are unimplemented. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. Declaring Interfaces The interface keyword is used to declare an interface.  The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.

Relationship between classes and interfaces

Output CSE UEM interface Bank{ float rateOfInterest(); } }   class SBI implements Bank{   public float rateOfInterest(){return 9.15f;}   class PNB implements Bank{   public float rateOfInterest(){return 9.7f;}   class TestInterface2{   public static void main(String[] args){   SBI b=new SBI();   System.out.println("ROI: "+b.rateOfInterest());   }}   interface myinterface{   void print();   }   class A implements  myinterface{   public void print() {System.out.println(“CSE UEM");}      public static void main(String args[]){   A obj = new A();   obj.print();    }   Output CSE UEM Output: ROI: 9.15

Multiple Inheritance in JAVA interface I1{   void print();   }   interface I2{   void show();   class A implements I1, I2 {   public void print(){System.out.println("Hello");}   public void show(){System.out.println(“CSE");}      public static void main(String args[]){   A obj = new A();   obj.print();   obj.show();    }   Output: Hello CSE

Multiple inheritance is not supported through class in java, but it is possible by an interface, why? multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. As you can see in the above example, I1and I2 interface have same methods but its implementation is provided by class MyInterface, so there is no ambiguity. interface I1{   void print();   }   interface I2{     class MyInterface implements I1, I2{   public void print(){System.out.println("Hello");}   public static void main(String args[]){   MyInterface  obj = new  MyInterface();   obj.print();    }   Output: Hello

Interface inheritance A class implements an interface, but one interface extends another interface. interface I1{   void print();   }   interface I2 extends I1{   void show();   class MyInterface implements I2{   public void print(){System.out.println("Hello");}   public void show(){System.out.println("Welcome");}      public static void main(String args[]){   MyInterface  obj = new  MyInterface();   obj.print();   obj.show();    }   } Output: Hello Welcome

Difference between abstract class and interface 1) Abstract class can have abstract and non-abstractmethods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) An abstract classcan extend another Java class and implement multiple Java interfaces. An interface can extend another Java interface only. 7) An abstract class can be extended using keyword extends An interface class can be implemented using keyword implements 8) A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default. 9)Example: public abstract class Shape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); }