INHERITANCE Mrs. K.M. Sanghavi

Size: px
Start display at page:

Download "INHERITANCE Mrs. K.M. Sanghavi"

Transcription

1 INHERITANCE Mrs. K.M. Sanghavi

2 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 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 parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship.

3 Use of inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

4 Syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called parent or super class and the new class is called child or subclass.

5 Java Inheritance Example As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

6 Java Inheritance Example class Employee{ float salary=40000; class Programmer extends Employee{ int bonus=10000; public static void main(string args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); Output : Programmer salary is: Bonus of programmer is:10000

7 Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

8 Single Inheritance Example class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void bark(){system.out.println("barking..."); class TestInheritance{ public static void main(string args[]){ Dog d=new Dog(); d.bark(); d.eat(); Output: barking... eating...

9 class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void bark(){system.out.println("barking..."); Multilevel Inheritance Example class BabyDog extends Dog{ void weep(){system.out.println("weeping...");

10 class TestInheritance2{ public static void main(string args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); Output: Multilevel Inheritance Example weeping... barking... eating...

11 Hierarchical Inheritance Example class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void bark(){system.out.println("barking..."); class Cat extends Animal{ void meow(){system.out.println("meowing...");

12 Hierarchical Inheritance Example class TestInheritance3{ public static void main(string args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//c.t.error Output: meowing... eating...

13 Method Overriding in Java If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

14 Usage of Java Method Overriding Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism

15 Rules for Java Method Overriding method must have same name as in the parent class method must have same parameter as in the parent class. must be IS-A relationship (inheritance).

16 Example of method overriding In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding. class Vehicle{ void run(){system.out.println("vehicle is running");

17 Example of method overriding class Bike2 extends Vehicle{ void run(){system.out.println("bike is running safely"); public static void main(string args[]){ Bike2 obj = new Bike2(); obj.run();

18 super keyword in java 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.

19 super keyword in java 1. super can be used to refer immediate parent class instance variable. 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor.

20 super : used to invoke immediate parent class instance variable. class Animal{ String color="white"; 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 white

21 super : used to refer immediate parent class method. class Animal{ void eat(){system.out.println("eating..."); 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... barking...

22 super : used to invoke immediate parent class conctructor. class Animal{ Animal(){System.out.println("animal is created"); class Dog extends Animal{ Dog(){ super(); Output System.out.println("dog is created"); class TestSuper3{ public static void main(string args[]){ Dog d=new Dog(); animal is created dog is created

23 Another super example class Person{ int id; String name; Person(int id,string name){ this.id=id; this.name=name;

24 Another super example continued class Emp extends Person{ float salary; Emp(int id,string name,float salary) { super(id,name);//reusing parent constructor this.salary=salary; void display(){system.out.println(id+" "+name+" "+salary);

25 Another super example continued class TestSuper5{ public static void main(string[] args) { Emp e1=new Emp(1,"ankit",45000f); e1.display(); Output: 1 ankit 45000

26 Final Keyword In Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class

27 Final Keyword In Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method Class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

28 Java final variable If you make any variable as final, you cannot change the value of final variable(it will be constant). class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; public static void main(string args[]){ Bike9 obj=new Bike9(); obj.run(); //end of class Output:Compile Time Error

29 Java final method If you make any method as final, you cannot override it. Example of final method class Bike{ final void run(){system.out.println("running"); class Honda extends Bike{ void run(){system.out.println("running safely with 100kmph"); //Error public static void main(string args[]){ Honda honda= new Honda(); honda.run(); Output: Compile Time Error

30 Java final class If you make any class as final, you cannot extend it. Example final class Bike{ class Honda1 extends Bike{ //Error void run(){system.out.println("running safely with 100kmph"); public static void main(string args[]){ Honda1 honda= new Honda(); honda.run(); Output:Compile Time Error

31 Blank or uninitialized final variable A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor.

32 Example of blank final variable class Student{ int id; String name; final String PAN_CARD_NUMBER;...

33 Dynamic Method Dispatch Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

34 Upcasting When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example: class A{ class B extends A{ A a=new B();//upcasting

35 Dynamic Method Dispatch Example class Bank{ float getrateofinterest(){return 0; class SBI extends Bank{ float getrateofinterest(){return 8.4f; class ICICI extends Bank{ float getrateofinterest(){return 7.3f; class AXIS extends Bank{ float getrateofinterest(){return 9.7f;

36 Dynamic Method Dispatch Example class TestPolymorphism{ public static void main(string args[]){ Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getrateofinterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getrateofinterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getrateofinterest());

37 Abstractionin Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. Ways to achieve Abstaction There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%)

38 Abstract class in Java A class that is declared with abstract keyword, is known as 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.

39 Abstract class in Java abstract class Shape{ abstract void draw(); //In real scenario, implementation is provided by others i.e. unk //nown by end user class Rectangle extends Shape{ void draw(){system.out.println("drawing rectangle"); class Circle1 extends Shape{ void draw(){system.out.println("drawing circle");

40 Abstract class in Java //In real scenario, method is called by programmer or u //ser class TestAbstraction1{ public static void main(string args[]){ Shape s=new Circle1();//In real scenario, object is provi //ded through method e.g. getshape() method s.draw();

41 Interface in Java An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.

42 Why use Java interface? There are mainly three reasons to use interface. They are given below. It is used to achieve abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.

43 Relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.

44 Java Interface Example In this example, Printable interface has only one method, its implementation is provided in the A class. interface printable{ void print(); class A implements printable{ public void print(){system.out.println("hello"); public static void main(string args[]){ A obj = new A(); obj.print();

45 Java Interface Example2 //Interface declaration: by first user interface Drawable{ void draw(); //Implementation: by second user class Rectangle implements Drawable{ public void draw(){system.out.println("drawing rectangle"); class Circle implements Drawable{ public void draw(){system.out.println("drawing circle");

46 Java Interface Example2 continued //Using interface: by third user class TestInterface1{ public static void main(string args[]){ Drawable d=new Circle(); //In real scenario, object is provided //by method e.g. getdrawable() d.draw();

47 Why multiple inheritance is not supported in java? 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 same method and you call it from child class object, there will be ambiguity to call 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 now.

48 class A{ void msg(){system.out.println("hello"); class B{ void msg(){system.out.println("welcome"); class C extends A,B{//suppose if it were public static void main(string args[]){ C obj=new C(); obj.msg();//now which msg() method would be invoked? Output : Compile Time Error

49 Multiple Inheritance in Java If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

50 Multiple Inheritance in Java interface Printable{ void print(); interface Showable{ void show(); class A implements Printable, Showable{ public void print(){system.out.println("hello"); public void show(){system.out.println("welcome"); public static void main(string args[]){ A obj = new A (); obj.print(); obj.show();

51 Interface inheritance A class implements interface but one interface extends another interface interface Printable{ void print(); interface Showable extends Printable{ void show(); class TestInterface4 implements Showable{ public void print(){system.out.println("hello"); public void show(){system.out.println("welcome"); public static void main(string args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show();

52 Difference between abstract class and interface Abstract class 1) Abstract class can have abstract and non-abstract methods. 2) Abstract class doesn't support multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. 4) Abstract class can provide the implementation of interface. 5) The abstract keyword is used to declare abstract class. 6) Example: public abstract class Shape{ public abstract void draw(); Interface Interface can have only abstract methods. Since Java 8, it can have default and static methods also. Interface supports multiple inheritance. Interface has only static and final variables. Interface can't provide the implementation of abstract class. The interface keyword is used to declare interface. Example: public interface Drawable{ void draw();

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

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. Inheritance in Java 1. Inheritance 2. Types of Inheritance 3. Why multiple inheritance is not possible in java in case of class? Inheritance in java is a mechanism in which one object acquires all the

More information

Answer1. Features of Java

Answer1. Features of Java Govt Engineering College Ajmer, Rajasthan Mid Term I (2017-18) Subject: PJ Class: 6 th Sem(IT) M.M:10 Time: 1 hr Q1) Explain the features of java and how java is different from C++. [2] Q2) Explain operators

More information

Java static keyword static keyword

Java static keyword static keyword Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the

More information

Chapter 5. Inheritance

Chapter 5. Inheritance Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super

More information

Create a Java project named week10

Create a Java project named week10 Objectives of today s lab: Through this lab, students will examine how casting works in Java and learn about Abstract Class and in Java with examples. Create a Java project named week10 Create a package

More information

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

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

this keyword in java javatpoint

this keyword in java javatpoint this keyword in java javatpoint There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Usage of java this keyword Here is given the 6

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

Method Overriding in Java

Method Overriding in Java Method Overriding in Java Whenever same method name is existing in both base class and derived class with same types of parameters or same order of parameters is known as method Overriding. Method must

More information

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism

More information

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing Unit 3 INFORMATION HIDING & REUSABILITY Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing Interfaces interfaces Using the keyword interface, you can fully abstract

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Unit 4 - Inheritance, Packages & Interfaces

Unit 4 - Inheritance, Packages & Interfaces 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.

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

K.Yellaswamy Assistant Professor CMR College of Engineering & Technology

K.Yellaswamy Assistant Professor CMR College of Engineering & Technology UNIT-II Inheritance Inheritance: It creates new classes from existing classes,so that the new classes will aquire all the fetures of the existing classes is called Inheritance. Father and Child relationship

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

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

SRI VIDYA COLLEGE OF ENGG & TECH UNIT -2 INHERITANCE AND INTERFACES SVCET Inheritance and Interfaces 2.1 UNIT -2 INHERITANCE AND INTERFACES 2.1 Inheritance Inheritance is the mechanism in java by which one class is allow to inherit the features (fields and methods) of another

More information

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

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

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 In Previous Lecture We

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

COLLEGE OF ENGINEERING, NASHIK

COLLEGE OF ENGINEERING, NASHIK Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK 3. Core Java Computer Dept. 30 th June 2017 Agenda 1. What is JAVA? 2. Features of Java 3. Hello World Program 4. Brief Concept JDK, JRE and JVM 5.

More information

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: has a CSE143 Sp Student. CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches

More information

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

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab

More information

Abstract class & Interface

Abstract class & Interface Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) Lab 3 Abstract class & Interface Eng. Mohammed Abdualal Abstract class 1. An abstract

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 09 Inheritance What is Inheritance? In the real world: We have general terms for objects in the real

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: has a CSC Employee. Supervisor CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

1 - Basics of Java. Explain features of JAVA.

1 - Basics of Java. Explain features of JAVA. 1 - Basics of Java Explain features of JAVA. Features of java is discussed below: Simple Java was designed to be easy for the professional programmer to learn and use effectively. Java is easy to master.

More information

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

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java Write a program in Java to create a player class. Inherit the classes Cricket_player, Football_player and Hockey_player from player class. The objective of this assignment is to learn the concepts of inheritance

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

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

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence. Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

CS8392 /Object Oriented Programming

CS8392 /Object Oriented Programming UNIT II INHERITANCE AND INTERFACES Inheritance Super classes- sub classes Protected members constructors in sub classes- the Object class abstract classes and methods- final methods and classes Interfaces

More information

Basics of Object Oriented Programming FCITR MAGAZINE DR. SHAKEEL AHMAD

Basics of Object Oriented Programming FCITR MAGAZINE DR. SHAKEEL AHMAD Basics of Object Oriented Programming FCITR MAGAZINE DR. SHAKEEL AHMAD FACULTY OF COMPUTING AND INFORMATION TECHNOLOGY AT RABIGH KING ABDULAZIZ UNIVERSITY KINGDOM SAUDI ARABIA Introduction Objects are

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

More information

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods Lecture 12 Summary Inheritance Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods Multiplicity 1 By the end of this lecture, you will

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding Java Class Design Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Objectives Implement encapsulation Implement inheritance

More information

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

More information

Inheritance & Polymorphism

Inheritance & Polymorphism Inheritance & Polymorphism Procedural vs. object oriented Designing for Inheritance Test your Design Inheritance syntax **Practical ** Polymorphism Overloading methods Our First Example There will be shapes

More information

OOP in Java Review. CS356 Object-Oriented Design and Programming October 1, 2014

OOP in Java Review. CS356 Object-Oriented Design and Programming   October 1, 2014 OOP in Java Review CS356 Object-Oriented Design and Programming http://cs356.yusun.io October 1, 2014 Yu Sun, Ph.D. http://yusun.io yusun@csupomona.edu Announcement Submit your GitHub username as soon

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3. oop #oop Table of Contents About 1 Chapter 1: Getting started with oop 2 Remarks 2 Examples 2 Introduction 2 OOP Introduction 2 Intoduction 2 OOP Terminology 3 Java 3 C++ 3 Python 3 Java 4 C++ 4 Python

More information

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

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (C) Name:. Status:

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Object Orientated Programming Details COMP360

Object Orientated Programming Details COMP360 Object Orientated Programming Details COMP360 The ancestor of every action is a thought. Ralph Waldo Emerson Three Pillars of OO Programming Inheritance Encapsulation Polymorphism Inheritance Inheritance

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

Subclasses, Superclasses, and Inheritance

Subclasses, Superclasses, and Inheritance Subclasses, Superclasses, and Inheritance To recap what you've seen before, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass.

More information

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

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

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class? Which statement is correct about overriding private methods in the super class? Peer Instruction Polymorphism Please select the single correct answer. A. Any derived class can override private methods

More information

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed 1 1 COMP200 ABSTRACT CLASSES OOP using Java, from slides by Shayan Javed Abstract Classes 2 3 From the previous lecture: public class GeometricObject { protected String Color; protected String name; protected

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (B) Name:. Status:

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

QUESTIONS FOR AVERAGE BLOOMERS

QUESTIONS FOR AVERAGE BLOOMERS MANTHLY TEST JULY 2017 QUESTIONS FOR AVERAGE BLOOMERS 1. How many types of polymorphism? Ans- 1.Static Polymorphism (compile time polymorphism/ Method overloading) 2.Dynamic Polymorphism (run time polymorphism/

More information

Object-Oriented Programming

Object-Oriented Programming Abstract classes Object-Oriented Programming Outline Abstract classes Abstract methods Design pattern: Template method Dynamic & static binding Upcasting & Downcasting Readings: HFJ: Ch. 8. GT: Ch. 8.

More information

Lesson 10. Work with Interfaces and Abstract Classes. Copyright all rights reserved

Lesson 10. Work with Interfaces and Abstract Classes. Copyright all rights reserved Lesson 10 Work with Interfaces and Abstract Classes Copyright 1999-2000 all rights reserved Lesson Objectives Upon completion of this lesson you should be able to Create an interface Implement an interface

More information

Inheritance, polymorphism, interfaces

Inheritance, polymorphism, interfaces Inheritance, polymorphism, interfaces "is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a

More information

Object Oriented Java

Object Oriented Java Object Oriented Java I. Object based programming II. Object oriented programing M. Carmen Fernández Panadero Raquel M. Crespo García Contents Polymorphism Dynamic binding Casting.

More information

Programming in C# Inheritance and Polymorphism

Programming in C# Inheritance and Polymorphism Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data

More information

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class,

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1 Inheritance Reuse of code Extension and intension Class specialization and class extension Inheritance The protected keyword revisited Inheritance and methods Method redefinition The composite design pattern

More information

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

IT101. Inheritance, Encapsulation, Polymorphism and Constructors IT101 Inheritance, Encapsulation, Polymorphism and Constructors OOP Advantages and Concepts What are OOP s claims to fame? Better suited for team development Facilitates utilizing and creating reusable

More information

Crash Course Review Only. Please use online Jasmit Singh 2

Crash Course Review Only. Please use online Jasmit Singh 2 @ Jasmit Singh 1 Crash Course Review Only Please use online resources @ Jasmit Singh 2 Java is an object- oriented language Structured around objects and methods A method is an action or something you

More information