Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions. Avoiding duplication and redundancy.

Slides:



Advertisements
Similar presentations
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
OOP: Inheritance By: Lamiaa Said.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
1 Overloading vs. Overriding b Don't confuse the concepts of overloading and overriding b Overloading deals with multiple methods in the same class with.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Lecture 3. 2 Introduction Java is a true OO language -the underlying structure of all Java programs is classes. Everything must be encapsulated in a class.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
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.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance, Abstract & Interface Pepper With help from and
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
Inheritance (Part 4) Abstract Classes 1.  sometimes you will find that you want the API for a base class to have a method that the base class cannot.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
1 Interface &Implements. 2 An interface is a classlike construct that contains only constants variables and abstract methods definition. An interface.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Remember this: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; // of type Animal an_arr[1] = a_dog ; //of type Dog an_arr[2] = a_wolf; // of type Wolf.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
BY:- TOPS Technologies
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Lecture 5:Interfaces and Abstract Classes
Inheritance.
Web Design & Development Lecture 9
Chapter 15 Abstract Classes and Interfaces
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
Lecture 12 Inheritance.
Inheritance and Polymorphism
Week 8 Lecture -3 Inheritance and Polymorphism
Chapter 13 Abstract Classes and Interfaces
Objects in other classes:
More on Classes & Arrays
CSC 113 Tutorial QUIZ I.
More inheritance, Abstract Classes and Interfaces
CS18000: Problem Solving and Object-Oriented Programming
Inheritance Inheritance is a fundamental Object Oriented concept
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 13 Abstract Classes and Interfaces Part 01
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions. Avoiding duplication and redundancy Classes inthe lower hierarchy is called a subclass (or derived, child, extended class). A class in the upper hierarchy is called a superclass (or base, parent class). Place all common variables and methods in the superclass Place specialized variables and methods in the subclasses redundancy reduced as common variables and methods are not repeated in all the subclasses.

In java, you use the word “extends” in the class definition to indicate a class is a subclass of another class, e.g., class Goalkeeper extends SoccerPlayer {......} class ChemStudent extends Student {.....} class Cylinder extends Circle {......}

public class Circle { private double radius; private double circumference; private double area; public Circle() { this(3.1); } public Circle(double rad) { radius = rad; circumference = getCirc(); area = getArea(); } public double getRad() { return radius; } public void setRad(double rad) { radius = rad; circumference = getCirc(); area = getArea(); } public double getCirc() { return (2.0 *radius * Math.PI); } public double getArea() { return(radius * radius * Math.PI); } public class Cylinder extends Circle { private double height; // Private field for only Cylinder objects public Cylinder(double radius, double h) { // Constructor super(radius); // invoke superclass' constructor height = h; } public Cylinder(double h) { super(); height = h; } public double getHeight() { return height; } public void setHeight(double h) { height = h; } public double getVolume() { return getArea()*height; // Use Circle's getArea() } public static void main(String[] args) { Circle x = new Circle(4.2); System.out.format("Circle Area: %5.2f\n", x.getArea()); System.out.format("Circle Circumference: %5.2f\n",x.getCirc()); Cylinder y = new Cylinder(3.0, 2.0); System.out.format("Cylinder Area: %5.2f\n",y.getArea()); System.out.format("Cylinder Circumference: %5.2f\n",y.getCirc()); System.out.format("Cylinder Volume: %5.2f\n",y.getVolume()); }

public static void main(String[] args) { Circle x = new Circle(4.2); System.out.format("Circle Area: %5.2f\n", x.getArea()); System.out.format("Circle Circumference: %5.2f\n",x.getCirc()); Cylinder y = new Cylinder(3.0, 2.0); System.out.format("Cylinder Area: %5.2f\n",y.getArea()); System.out.format("Cylinder Circumference: %5.2f\n",y.getCirc()); System.out.format("Cylinder Volume: %5.2f\n",y.getVolume()); } Circle Area: Circle Circumference: Cylinder Area: Cylinder Circumference: Cylinder Volume: 56.55

public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; } public void sleep() { System.out.println("Animal is sleeping"); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { public String breed; public Dog(){ super(); breed = “Mutt” } public Dog(String name, String breed) { this(true,name,breed); } public Dog(boolean pet, String name, String breed) { super(pet, name); this.breed = breed; } public void move() { System.out.println("Frolicking forward"); } public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); System.out.println(an_x.name); System.out.println(an_x.isaPet); an_x.sleep(); an_x.talk(); Dog a_dog = new Dog("Spot“,”pug”); System.out.println(a_dog.name); System.out.println(a_dog.isaPet); System.out.println(a_dog.breed); a_dog.sleep(); a_dog.talk(); a_dog.move(); } } What fields and methods are part of an_x? What fields and methods are part of a_dog?

Do you see a problem? class A { public A(int x) { } class B extends A { public B() { } class C { public static void main(String[] args) { B b = new B(); }

public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; } public void sleep() { System.out.println("Animal is sleeping"); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { public String breed; public Dog(){ super(); breed = “Mutt” } public Dog(String name, String breed) { this(true,name,breed); } public Dog(boolean pet, String name, String breed) { super(pet, name); this.breed = breed; } public void move() { System.out.println("Frolicking forward"); } public void talk() { System.out.println(“bark bark"); } public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); System.out.println(an_x.name); System.out.println(an_x.isaPet); an_x.sleep(); an_x.talk(); // what does this line do? Dog a_dog = new Dog("Spot“,”pug”); System.out.println(a_dog.name); System.out.println(a_dog.isaPet); System.out.println(a_dog.breed); a_dog.sleep(); a_dog.talk(); // what does this line do? a_dog.move(); } } What methods and fields does a_dog have? What happens when a_dog.talk() is executed?

Overriding! When in a subclass you write a method that overrides a method with the same name in its parent class. In essence, you’ve got a default method in the superclass And then you have a more specific (and accurate) method belonging to the subclass Every subclass can have its own default method that overrides the superclass’s method

public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; } public void sleep() { System.out.println("Animal is sleeping"); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void move() { System.out.println("Frolicking forward"); } public void talk() { System.out.println("bark bark"); } public class Wolf extends Dog { public Wolf(){ super(false,"noName"); } public void move() { System.out.println("running intently"); } public void stalk() { System.out.println("stalking my prey"); } public void talk() { System.out.println("howl"); super.talk(); } public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); // what methods and fields are available to an_x? Dog a_dog = new Dog("Spot"); // what methods and fields are available to a_dog? Wolf a_wolf = new Wolf(); // what methods and fields are available to a_wolf? }

public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; } public void sleep() { System.out.println("Animal is sleeping"); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { public String breed; public Dog(){ super(); breed = “Mutt”; } public Dog(String name) { super(true, name); breed = “Mutt”; } public Dog(boolean pet, String name, String breed) { super(pet, name); this.reed = breed; } public void move() { System.out.println("Frolicking forward"); } public void talk() { System.out.println("bark bark"); } public class Wolf extends Dog { public Wolf(){ super(false,"noName“, “wolf”); } public void move() { System.out.println("running intently"); } public void stalk() { System.out.println("stalking my prey"); } public void talk() { System.out.println("howl"); super.talk(); } public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); System.out.println(an_x.name); System.out.println(an_x.isaPet); an_x.sleep(); an_x.talk(); Dog a_dog = new Dog("Spot"); System.out.println(a_dog.name); System.out.println(a_dog.isaPet); a_dog.sleep(); a_dog.talk(); a_dog.move(); Wolf a_wolf = new Wolf(); System.out.println(a_wolf.name); System.out.println(a_wolf.isaPet); a_wolf.sleep(); a_wolf.talk(); a_wolf.move(); a_wolf.stalk(); }

Coolness: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; an_arr[1] = a_dog; an_arr[2] = a_wolf; for (int i = 0; i < 3; i++) { an_arr[i].talk(); if (an_arr[i].isaPet) { System.out.println(an_arr[i].name); } } // what gets printed? // could I do an_arr[i].breed? (breed is a field in the dog class) // can I do an_arr[1].breed?

Only methods and fields in superclass can be accessed automatically: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; an_arr[1] = a_dog; an_arr[2] = a_wolf; for (int i = 0; i < 3; i++) { an_arr[i].talk(); if (an_arr[i].isaPet) { System.out.println(an_arr[i].name); } Dog tempd = (Dog)an_arr[1]; System.out.println(tempd.breed);

Overriding public class Musician { public void play() { System.out.println(“silence”); } public class Drummer extends Musician { public void play() { System.out.println(“boom boom”); } public class Guitarist extends Musician { public void play() { System.out.println(“twang”); }... Musician musician = new Guitarist(); musician.play(); What is the output? twang

Overriding public class Musician { public void play() { System.out.println(“silence”); } public class Drummer extends Musician { public void play() { System.out.println(“boom boom”); } public class Guitarist extends Musician { public void play() { System.out.println(“twang”); super.play(); }... Musician musician = new Guitarist(); musician.play(); musician = new Drummer(); musician.play(); What is the output? twang silence boom

public class Animal { public boolean isaPet; public String name; public boolean isaWolf; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); } public Animal(boolean pet, String name, boolean isawolf) { isaPet = pet; this.name = name; this.isaWolf = isawolf; } public void sleep() { System.out.println("Animal is sleeping"); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void move() { System.out.println("Going forward"); } public void talk() { System.out.println("bark bark"); } public class Wolf extends Dog { public Wolf(){ super(false,"noName",true); } public void move() { System.out.println("running intently"); } public void stalk() { System.out.println("stalking my prey"); } public void talk() { System.out.println("howl"); super.talk(); } … Wolf x = new Wolf(); Animal x = new Wolf(); Will this work? How can we fix this?

public class Animal { public boolean isaPet; public String name; public boolean isaWolf; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); } public Animal(boolean pet, String name, boolean isawolf) { isaPet = pet; this.name = name; this.isaWolf = isawolf; } public void sleep() { System.out.println("Animal is sleeping"); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public Dog(boolean pet, String name,boolean isawolf) { super(pet, name,isawolf); } public void move() { System.out.println("Going forward"); } public void talk() { System.out.println("bark bark"); } public class Wolf extends Dog { public Wolf(){ super(false,"noName",true); } public void move() { System.out.println("running intently"); } public void stalk() { System.out.println("stalking my prey"); } public void talk() { System.out.println("howl"); super.talk(); } … Wolf x = new Wolf(); Animal x = new Wolf();

Public/Private and inheritance Public: Anything in the superclass that is declared public is available to all subclasses (and everything else) Private – only the superclass has access to it Subclasses don’t have access

public class Animal { public boolean isaPet; public String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void talk() { System.out.println(name+“ says bark bark"); } This works

public class Animal { public boolean isaPet; private String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void talk() { System.out.println(name+“ says bark bark"); } This doesn’t work – use a getter

public class Animal { public boolean isaPet; private String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); } public String getName() { return(name); } public void talk() { System.out.println("talking"); } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void talk() { System.out.println(getName()+“ says bark bark"); } This works

How many problems do you see? public class Circle { double radius; public Circle(double radius) { radius = radius; } public double getRadius() { return radius; } public double getArea() { return radius * radius * Math.PI; } public class B extends Circle { double length; public B(double radius, double length) { Circle(radius); } public double getArea() { return getArea() * length; }

Abstract Methods Suppose you have many class behaviors that have a common first step and a common last step The middle step is different Wouldn’t it be nice if you could write this code once: public void commonBehavior() { //... code that does first step doMiddleStep(); //... code that does last step }

You can! public void commonBehavior() { //... code that does first step doMiddleStep(); //... code that does last step } public abstract void doMiddleStep();

Abstract Classes Declared using the abstract keyword abstract class Cannot be instantiated (can’t make an object from this class) Must be a superclass to other classes fields, methods and constructors are accessed in the same way as with the other subclasses. abstract methods methods without any implementation must be overridden by a subclass // forces you to write a definition of the method in the subclass Abstract methods can be implemented within the abstract class A class must be abstract if it has abstract methods

abstract class Animal { public boolean isaPet; public String name; public Animal() { this(true,"Fred"); } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; } public String getName() { return name; } abstract void talk(); public void talking() { System.out.print(“The animal says "); talk(); System.out.println(“ and then it is quiet.”) } public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); } public Dog(boolean pet, String name) { super(pet, name); } public void talk() { System.out.println("bark bark"); } public class Main{ public static void main(String[] args) { Dog a_dog = new Dog("Spot"); a_dog.talking(); } } … The animal says: bark bark and then it is quiet What is output?

Which of these is legal? class A { abstract void unfinished() { } public class abstract A { abstract void unfinished(); } class A { abstract void unfinished(); } abstract class A { void unfinished(); } abstract class A { void unfinished() { } A B C D E

Interfaces contains only constants and abstract methods Unlike abstract classes they cannot have fields (properties) or implemented methods (methods with code in them)

29 Define an Interface To distinguish an interface from a class, Java uses the following syntax to define an interface: public interface InterfaceName { constant declarations; //constants!! Things you give a value to and never touch again other //than to use the value method signatures; } Example : public interface Edible { /** Describe how to eat */ public abstract String howToEat(); public abstract String howToDrink(); public abstract Boolean isEdible(Food fooditem); }

Why Interfaces? Remember, all subclasses of an interface must implement (make code for) each method in the interface

31 Laziness All fields in an interface MUST BE public static (e.g., constants) All methods MUST BE public abstract For this reason, these modifiers can be omitted, as shown below: A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME e.g., T1.K

public interface AnimalInterface { abstract public String talks(); abstract public String eats(); abstract public String moves(); } class Cat implements AnimalInterface { public Cat() { } public String talks(){ return("meow meow"); } public String eats(){ return("Eats mice"); } public String moves(){ return("prowls"); } public class Bunny implements AnimalInterface{ public Bunny() { } public String talks(){ return("no idea"); } public String eats(){ return("Eats hay"); } public String moves(){ return("hops"); } public class Cow implements AnimalInterface{ public Cow() { } public String talks(){ return("moo moo"); } public String eats(){ return("Eats grass"); } public String moves(){ return("rarely runs"); } public static void main(String[] args) { AnimalInterface[] arr = new AnimalInterface[3]; arr[0] = new Cow(); arr[1] = new Cat(); arr[2] = new Bunny(); for (AnimalInterface x: arr) { System.out.println(x.talks()); System.out.println(x.moves()); System.out.println(x.eats()); }

Using interfaces Interfaces are not part of the class hierarchy A class may implement many different interfaces Polymorphism still holds An instance of class X that implements interface Y can be used as the base interface type: Y myY = new X();

public interface AnimalInterface { abstract public String talks(); abstract public String eats(); abstract public String moves(); } public interface FarmThings { abstract public boolean isaFarmTool(); abstract public String produces(); } public class Cow implements AnimalInterface, FarmThings{ public Cow() { } public String talks(){ return("moo moo"); } public String eats(){ return("Eats grass"); } public String moves(){ return("rarely runs"); } public boolean isaFarmTool(){ return false; } public String produces(){ return "milk"; }