Unit 4 - Inheritance, Packages & Interfaces

Similar documents
Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

CSCE3193: Programming Paradigms

OVERRIDING. 7/11/2015 Budditha Hettige 82

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Chapter 5. Inheritance

JAVA. Lab-9 : Inheritance

* Mrs. K.M. Sanghavi

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

1 Shyam sir JAVA Notes

PROGRAMMING LANGUAGE 2

What is Inheritance?

Inheritance. Transitivity

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Java Fundamentals (II)

Fundamentals of Object Oriented Programming

Third Year Diploma Courses in Computer Science & Engineering, Computer Engineering, Computer Technology & Information Technology Branch.

Inheritance and Interfaces

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

QUESTIONS FOR AVERAGE BLOOMERS

Subclasses, Superclasses, and Inheritance

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

INHERITANCE Mrs. K.M. Sanghavi

CS-202 Introduction to Object Oriented Programming

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance and Polymorphism

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

Hierarchical abstractions & Concept of Inheritance:

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

JAVA: A Primer. By: Amrita Rajagopal

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Java Professional Certificate Day 1- Bridge Session

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CS260 Intro to Java & Android 03.Java Language Basics

INHERITANCE. Spring 2019

Unit 3 INFORMATION HIDING & REUSABILITY. -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Class, Variable, Constructor, Object, Method Questions

SRI VIDYA COLLEGE OF ENGG & TECH UNIT -2 INHERITANCE AND INTERFACES SVCET

K.Yellaswamy Assistant Professor CMR College of Engineering & Technology

POLYTECHNIC OF NAMIBIA SCHOOL OF COMPUTING AND INFORMATICS DEPARTMENT OF COMPUTER SCIENCE

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

Object Oriented Programming. Java-Lecture 11 Polymorphism

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

By: Abhishek Khare (SVIM - INDORE M.P)

C++ Important Questions with Answers

5. PACKAGES AND INTERFACES

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Chapter 14 Abstract Classes and Interfaces

STRUCTURING OF PROGRAM

CS 251 Intermediate Programming Inheritance

Java Object Oriented Design. CSC207 Fall 2014

UNIT -IV INHERITANCE, PACKAGES AND INTERFACES

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

What are the characteristics of Object Oriented programming language?

More Relationships Between Classes

COP 3330 Final Exam Review

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Packages. Examples of package names: points java.lang com.sun.security drawing.figures

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Rules and syntax for inheritance. The boring stuff

Simple Java Programs. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Inheritance and Polymorphism

Programming overview

Starting Out with Java: From Control Structures Through Objects Sixth Edition

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Programming II (CS300)

Lecture 2: Java & Javadoc

Inheritance -- Introduction

Basics of Object Oriented Programming. Visit for more.

core Advanced Object-Oriented Programming in Java

Unit 5 - Exception Handling & Multithreaded

Inheritance (continued) Inheritance

Advanced Object-Oriented. Oriented Programming in Java. Agenda. Overloading (Continued)

Inheritance. The Java Platform Class Hierarchy

Inheritance Definition Single Inheritance Benefits of inheritance Member access rules super classes Polymorphism Method overriding Using final with

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Practice for Chapter 11

CS260 Intro to Java & Android 02.Java Technology

Lecture 18 CSE11 Fall 2013 Inheritance

Chapter 10 Classes Continued. Fundamentals of Java

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

ITI Introduction to Computing II

Exercise: Singleton 1

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Constructor in Java. What is a Constructor? Rules for create a Java Constructor

First IS-A Relationship: Inheritance

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Transcription:

Inheritance Inheritance is the process, by which class can acquire the properties and methods of its parent class. The mechanism of deriving a new child class from an old parent class is called inheritance. The new class is called derived class and old class is called base class. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. All the properties of superclass except private properties can be inherit in its subclass using extends keyword. Types of Inheritance Single Inheritance A B If a class is derived from a single class then it is called single inheritance. Class B is derived from class A. Multilevel Inheritance A B A class is derived from a class which is derived from another class then it is called multilevel inheritance Here, class C is derived from class B and class B is derived from class A, so it is called multilevel inheritance. C Multiple Inheritance A B If one class is derived from more than one class then it is called multiple inheritance. It is not supported in java through class. C Hierarchical Inheritance A If one or more classes are derived from one class then it is called hierarchical inheritance. Here, class B, class C and class D are derived from class A. B C D Hybrid Inheritance Hybrid inheritance is combination of single and multiple A inheritance. But java doesn't support multiple inheritance, so the hybrid B C inheritance is also not possible. D 1 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Example class A public void displaya() System.out.println("class A method"); class B extends A //Single Inheritance - class B is derived from class A public void displayb() System.out.println("class B method"); class C extends B // Multilevel Inheritance - class C is derived from class B public void displayc() System.out.println("class C method"); class D extends A //Hierarchical Inheritance - Class B and Class D are derived from Class A public void displayd() System.out.println("class D method"); class Trial public static void main(string []args) B b=new B(); C c=new C(); D d=new D(); b.displayb(); c.displayc(); d.displayd(); 2 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

o Class B and class D are derived from class A so it is example of Hierarchal Inheritance. Method Overriding When a method in a subclass has the same name and type signature as method in its superclass, then the method in the subclass is said to override the method of the super class. The benefit of overriding is: Ability to define a behavior that's specific to the subclass type. Which means a subclass can implement a superclass method based on its requirement. Method overriding is used for runtime polymorphism. In object oriented terms, overriding means to override the functionality of any existing method. class A public void display() System.out.println("Class A"); class B extends A public void display() System.out.println("Class B"); class Trial A a = new A(); // A reference and object A b = new B(); // A reference but B object a.display(); // Runs the method in A class b.display(); // Runs the method in B class Class A Class B o In the above example, you can see that even though b is a type of A it runs the display() method of the B class. o Because, at compile time reference type of object is checked. However, at the runtime JVM determine the object type and execute the method that belongs to that particular object. Rules for method overriding The argument list should be exactly the same as that of the overridden method. 3 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

The return type should be the same as the return type declared in the original overridden method in the superclass. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. Constructors cannot be overridden. super keyword The super keyword in java is a reference variable that is used to refer immediate parent class object. super To Access super-class Members If your method overrides one of its super-class methods, you can invoke the overridden method through the use of the keyword super. class A String name = "Class A"; public void display() System.out.println("Class A display method called.."); class B extends A String name = "Class B"; public void display() System.out.println("Class B display method called.."); void printname() //this will print value of name from subclass(b) System.out.println("Name from subclass : " + name); // this will print value of name from superclass(a) System.out.println("Name from Superclass: " + super.name); 4 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

//invoke display() method of Class B method display(); // invoke display() method of class A(superclass) using super super.display(); class SuperDemo B b1 = new B(); b1.printname(); Name from subclass : Class B Name from Superclass: Class A Class B display method called.. Class A display method called.. o Here, display() method of subclass overrides the display() method of its super-class. o So, to call superclass(a) members within subclass(b) super keyword is used. super To Call super-class Constructor Every time a parameterized or non-parameterized constructor of a subclass is created, by default a default constructor of superclass is called implicitly. The syntax for calling a superclass constructor is: super(); OR super(parameter list); The following example shows how to use the super keyword to invoke a superclass's constructor. class A A() System.out.println("Super class default constructor called.."); A(String s1) System.out.println("Super class parameterized constructor called: "+s1); class B extends A 5 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

/* Implicitly default constructor of superclass(a) will be called. Whether you define super or not in subclass(b) constructor */ B() System.out.println("Sub class default constructor called.."); /* To call a parameterized constructor of superclass(a) you must write super() with same number of arguments*/ B(String s1) super("class A"); System.out.println("Sub class parameterized constructor called: " + s1); class SuperConDemo B b1 = new B(); B b2 = new B("Class B"); Super class default constructor called.. Sub class default constructor called.. Super class parameterized constructor called: Class A Sub class parameterized constructor called: Class B Here, implicitly a default constructor of superclass is called not a parameterized one. To call a parameterized constructor of a superclass we must use 'super(parameters..)' with matching parameters. Dynamic Method Dispatch Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. It is also known as run-time polymorphism. A superclass reference variable can refer to a subclass object. It is known as Upcasting. When an overridden method is called through a superclass reference, the determination of the method to be called is based on the object being referred to by the reference variable. This determination is made at run time. class A void callme() 6 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

System.out.println("Inside A's callme method"); class B extends A void callme() System.out.println("Inside B's callme method"); class C extends A void callme() System.out.println("Inside C's callme method"); class DispatchDemo A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain r a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme() r = b; // r refers to a B object r.callme(); // calls B's version of callme() r = c; // r refers to a C object r.callme(); // calls C's version of callme() Inside A's callme method Inside B's callme method Inside C's callme method Object Class The Object class is the parent class (java.lang.object) of all the classes in java bydefault. The Object class provides some common behaviors to all the objects must have, such as object can be compared, object can be converted to a string, object can be notified etc.. Some Java object class methods are given below: Method equals() To compare two objects for equality. Description 7 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

getclass() tostring() notify() notifyall() wait() Returns a runtime representation of the class of this object. By using this class object we can get information about class such as its name, its superclass etc. Returns a string representation of the object. Wakes up single thread, waiting on this object's monitor. Wakes up all the threads, waiting on this object's monitor. Causes the current thread to wait, until another thread notifies. class parent inti = 10; Integer i1 = new Integer(i); void PrintClassName(Object obj) // Pass object of class as an argument System.out.println("The Object's class name is ::" + obj.getclass().getname()); class ObjectClassDemo parent a1 = new parent(); a1.printclassname(a1); System.out.println("String representation of object i1 is:: "+a1.i1.tostring()); The Object's class name is :: parent String representation of object i1 is:: 10 Packages A java package is a group of similar types of classes, interfaces and sub-packages. Packages are used to prevent naming conflicts and provides access protection. It is also used to categorize the classes and interfaces. so that, they can be easily maintained. We can also categorize the package further by using concept of subpackage. Package inside the package is called the subpackage. Package can be categorized in two form: built-in package and user-defined package. o built-in packages :Existing Java package such as java.lang, java.util, java.io, java.net, java.awt. o User-defined-package : Java package created by user to categorized classes and interface. Programmers can define their own packages to bundle group of classes, interfaces etc. Creating a package To create a package, package statement followed by the name of the package. 8 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

The package statement should be the first line in the source file. There can be only one package statement in each source file. If a package statement is not used then the class, interfaces etc. will be put into an unnamed package. package mypack; class Book String bookname; String author; Book() bookname = "Complete Reference"; author = "Herbert"; void show() System.out.println("Book name is :: "+bookname+"\nand author name is :: "+ author); class DemoPackage public static void main(string[] args) Book b1 = new Book(); b1.show(); Compile: javac -d. DemoPackage.java To run the program : java mypack.demopackage Book name is :: Complete Reference and author name is :: Herbert o The -d is a switch that tells the compiler where to put the class file. Like, /home (Linux), d:/abc (windows) etc. o The. (dot) represents the current folder. Import Package import keyword is used to import built-in and user-defined packages into your java source file. If a class wants to use another class in the same package, no need to import the package. But, if a class wants to use another class that is not exist in same package then import keyword is used to import that package into your java source file. A class file can contain any number of import statements. There are three ways to access the package from outside the package: 9 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

1) import package.*; 2) import package.classname; 3) fully qualified name 1) Using packagename.* : o If you use packagename.* then all the classes and interfaces of this package will be accessible but not subpackages. Syntax: import packagename.*; 2) Using packagename.classname : o If you use packagename.classname then only declared class of this package will be accessible. Syntax: import packagename.classname; 3) Using fully qualified name : o If you use fully qualified name then only declared class of this package will be accessible. So, no need to import the package. o But, you need to use fully qualified name every time when you are accessing the class or interface. o It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. File 1: A.java package pack; public class A public void display() System.out.println("Welcome to package pack..."); File 2: Q.java package pack; public class Q public void Q_display() System.out.println("Welcome to package pack through qualified name..."); File 3: B.java package mypack; import pack.*; // Here, you can also use import pack.a ; class B 10 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

A a1 = new A(); pack.q q1= new pack.q(); /*Here Q is class in package A. If you want to access Q_display() method of class Q using fully qualified name then no need to import package named pack */ a1.display(); q1.q_display(); java mypack.b Welcome to package pack... Welcome to package pack through qualified name... o In above example, class A, class Q and all its methods must be declared as public otherwise they can be access in class B. Visibility and Access Rights Interfaces class \ have access to Private Default Protected Public own class yes yes yes yes subclass - same package no yes yes yes subclass - another package no no yes yes class - another package no no no yes An interface is a collection of abstract methods. An interface is not a class. When you create an interface it defines what a class can do without saying anything about how the class will do it. Interface contains only static constants and abstract methods only. The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. By default (Implicitly), an interface is abstract, interface fields(data members) are public, static and final and methods are public and abstract. It is used to achieve fully abstraction and multiple inheritance in Java. Similarity between class and interface are given below: o An interface can contain any number of methods. o An interface is written in a file with a.java extension, with the name of the interface matching the name of the file. o The bytecode of an interface appears in a.class file. Difference between class and interface are given below: Class Interface You can instantiate class. You cannot instantiate an interface. It contains default as well as parameterize constructors. It does not contain any constructors. 11 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

All the methods should have definition otherwise declare method as abstract explicitly. All the variables are instance by default. A class can inherit only one Class and can implement many interfaces. Declaring Interfaces All the methods in an interface are abstract by default. All the variables are static final by default, and a value needs to be assigned at the time of definition. An interface cannot inherit any class while it can extend many interfaces. The interface keyword is used to declare an interface. Syntax: NameOfInterface.java import java.lang.*; public interface NameOfInterface //Any number of final, static fields //Any number of abstract method declarations DemoInterface.java interface DemoInterface int i = 10; void demo(); o In above example, name of interface is DemoInterface and it contains a variable i of integer type and an abstract method named demo(). Implementing Interfaces A class uses the implements keyword to implement an interface. A class implements an interface means, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. DemoInterfaceImp.java public class DemoInterfaceImp implements DemoInterface public void demo() System.out.println("Value of i is :: "+i); DemoInterfaceImp d = new DemoInterfaceImp(); d.demo(); 12 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Value of i is :: 10 Inheritance on Interfaces We all knows a class can extend another class. Same way an interface can extend another interface. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. public interface A void getdata(string name); public interface B extends A void setdata(); class InheritInterface implements B String display; public void getdata(string name) display = name; public void setdata() System.out.println(display); InheritInterface obj = new InheritInterface(); obj.getdata("welcome TO Heaven"); obj.setdata(); Welcome TO Heaven o The interface B has one method, but it inherits one from interface A; thus, a class InheritInterface that implements B needs to implement two methods. Multiple Inheritance using Interface If a class implements multiple interfaces, or an interface extends multiple interfaces known as multiple inheritance. 13 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

A java class can only extend one parent class. Multiple inheritances are not allowed. However, an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. public interface A void getdata(string name); public interface B extends A,C*/ void setdata(); class InheritInterface implements A, B String display; public void getdata(string name) display = name; public void setdata() System.out.println(display); InheritInterface obj = new InheritInterface(); obj.getdata("welcome TO Heaven"); obj.setdata(); Welcome TO Heaven /* Here we can also extends multiple interface like interface B Abstract Class A class that is declared with abstract keyword, is known as an abstract class in java. It can have abstract and non-abstract methods (method with body). It needs to be extended and its method implemented. It cannot be instantiated means we can t create object of it. Any class that extends an abstract class must implement all the abstract methods declared by the super class. Syntax: abstract classclass_name 14 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

//Number of abstract as well as non-abstract methods. A method that is declared as abstract and does not have implementation is known as abstract method. The method body will be defined by its subclass. Abstract method can never be final and static. Syntax: abstract return_typefunction_name (); // No definition abstract class A abstract void abs_method(); public void display() System.out.println("This is concrete method.."); class DemoAbstract extends A void abs_method() System.out.println("This is an abstract method.."); public static void main(string[] args) DemoAbstract abs = new DemoAbstract(); abs.abs_method(); abs.display(); This is an abstract method.. This is concrete method.. Final Keyword The final keyword in java is used to restrict the user. The java final keyword can be used with: 1) variable 2) method 3) class Final Variable: If you make any variable as final, you cannot change the value of that final variable (It will be constant). o A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialize it. Final Method: Methods declared as final cannot be overridden. Final Class: Java classes declared as final cannot be extended means cannot inherit. If you declare any parameter as final, you cannot change the value of it. 15 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

class DemoBase final inti = 1; //final variable must be initialize. final void display() System.out.println("Value of i is :: "+ i); class DemoFinal extends DemoBase Value of iis :: 1 /*void display() // Compilation error final method cannot override. System.out.println("Value of i is :: "+ i); */ DemoFinal obj = new DemoFinal(); obj.display(); Difference between Method Overloading and overriding Overriding The argument list must exactly match that of the overridden method. The return type must be the same as overridden method in the super class. Private and final methods cannot be overridden. Method overriding occurs in two classes that have inheritance. Dynamic bindingis being used for overridden methods. Method overriding is the example of run time polymorphism. Difference between Interface and Abstract class Interface Interface can have only abstract methods. Interface supports multiple inheritance. Overloading Overloaded methods MUST change the argument list. Overloaded methods CAN change the return type. Private and final methods can be overloaded. Method overloading is performed within class. Static binding is being used for overloaded methods. Method overloading is the example of compile time polymorphism. Abstract class Abstract class can have abstract and nonabstract methods. Abstract class doesn't support multiple inheritance. 16 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana

Interface can't have static methods, main method or constructor. In interface all method should be define in a class in which we implement them. Interface can't provide the implementation of abstract class. Abstract class can have static methods, main method and constructor. This is not applicable for abstract classes. Abstract class can provide the implementation of interface. 17 Dept: CE Java Programming(3350703) Prof. Vishal K. Makwana