More inheritance, Abstract Classes and Interfaces

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Chapter 1 Inheritance University Of Ha’il.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Abstract Classes and Interfaces The objectives of this chapter are: To explore the concept of abstract classes To understand interfaces To understand the.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Inheritance and Polymorphism CS180 Fall Definitions Inheritance – object oriented way to form new classes from pre-existing ones –Superclass The.
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
1 Topic 10 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.”
Inheritance using Java
COP 3003 Object-Oriented Programming - Polymorphism Dr. Janusz Zalewski, Fall 2013 Prepared by Dr Dahai Guo.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
1 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.” CS Computer Science II.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
LECTURE 9: INTERFACES & ABSTRACT CLASSES CSC 212 – Data Structures.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Web Design & Development Lecture 9
Chapter 15 Abstract Classes and Interfaces
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
Advanced Programming in Java
Chapter 11 Inheritance and Polymorphism
Inheritance-Basics.
Inheritance and Polymorphism
EKT 472: Object Oriented Programming
Week 8 Lecture -3 Inheritance and Polymorphism
Extending Classes.
Introduction interface in Java is a blueprint of a class. It has static constants and abstract methods only. An interface is a way to describe what classes.
Java Programming Language
Inheritance, Polymorphism, and Interfaces. Oh My
Week 6 Object-Oriented Programming (2): Polymorphism
Interfaces.
Topic 10 Abstract Classes “I prefer Agassiz in the abstract,
Advanced Java Programming
METHOD OVERRIDING in JAVA
CS18000: Problem Solving and Object-Oriented Programming
Java Inheritance.
Topic 10 Abstract Classes “I prefer Agassiz in the abstract,
Object Oriented Programming
Chapter 9 Carrano Chapter 10 Small Java
Overview of C++ Polymorphism
Chapter 14 Abstract Classes and Interfaces
Inheritance and Polymorphism
Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Abstract Classes and Interfaces
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
Advanced Programming in Java
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

More inheritance, Abstract Classes and Interfaces Week 9 More inheritance, Abstract Classes and Interfaces

Lecture Outline Inheritance Upcasting and downcasting instanceof Abstract class and methods Java Interface final keyword in Java

Upcasting and downcasting Upcasting Java supports an object of a subclass type to be treated as an object of any superclass type. It is done automatically. Downcasting It is to be performed manually by the developers.

Upcasting and downcasting contd. Object implicit Animal Cat Bird Downcasting

Upcasting and downcasting contd. Upcasting and downcasting are NOT like casting primitive datatypes from one to other By casting we are not actually changing the object itself, you are just labelling it differently

Upcasting and downcasting contd. Object implicit Animal Cat Bird Cat is-a Animal √ Animal is-a Cat X Animal is-a Bird X Downcasting Bird is-a Animal √

Upcasting and downcasting contd. Animal -name: String +sound(): void Cat +sound(): void Bird + sound() : void

Upcasting and downcasting contd. public class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public void sound() { System.out.println("No sound!");

Upcasting and downcasting contd. class Cat extends Animal { Cat (String name) { super(name); } public void sound() { System.out.println(name+" Meowing!");

Upcasting and downcasting contd. class Bird extends Animal { Bird (String name) { super(name); } public void sound() { System.out.println(name+" Tweeting!");

Upcasting and downcasting contd. class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal animal.sound(); } = new Animal(); Output: ? }

Upcasting and downcasting contd. class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal animal.sound(); } = new Animal(); Output: Bela Meowing! Happy Tweeting! No sound! }

Upcasting example class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal = new Animal(); animal = cat; //automatic upcasting animal.sound(); }

Upcasting example class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal = new Animal(); animal = cat; //automatic upcasting animal.sound(); Output: } Bela Meowing! Happy Tweeting! Bela Meowing! }

Downcasting example class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal = new Animal(); animal = cat; //automatic upcasting Cat cat2 = (Cat) animal;//downcasting manually cat2.sound(); } Output: Bela Meowing! Happy Tweeting! Bela Meowing! }

Observation (1) class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal = new Animal(); animal = cat; //automatic upcasting Bird bird2 = (Bird) animal;//downcasting?? bird2.sound(); } Output: ??

Observation(2) As in the Hierarchy we can have many different Animals, and if we want to downcast them all to Cat, what happens? For example, Cat to Bird But Cat is definitely not-a Bird Exception in thread "main" java.lang.ClassCastException: OOSD1.Cat cannot be cast to OOSD1.Bird This is because of Dynamic binding (although code will compile)

instanceof class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); Animal animal = new Animal(); animal = cat; //automatic upcasting if(animal instanceof Cat){ Cat cat2 = (Cat) animal;//downcasting } cat2.sound();

Observation(3) Incompatible types: Shape cannot be converted to Square class TestAnimal { public static void main(String[] args) { Cat cat = new Animal(); } Incompatible types: Shape cannot be converted to Square

Abstract class

How classes are designed Super classes are created through the process called "generalization" Common features (methods/variables) are factored out of object classifications Those features are formalized in a class This becomes the superclass The classes from which the common features were taken become subclasses to the newly created super class

How classes are designed contd. Often, the superclass does not have a "meaning" or does not directly relate to a "thing" in the real world It is an artefact of the generalization process Because of this, abstract classes cannot be instantiated They act as place holders for abstraction

Example Abstract base class named in Italic Animal -name: String +sound(): void Abstract base class named in Italic Cat +sound(): void Bird + sound() : void In this example, the subclasses represent objects (classes) taken from the problem domain. The superclass represents an abstract concept that does not exist "as is" in the real world.

Observation In the following, doesn’t seem like we have enough information to get the sound() if all we know is it is an Animal. public class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public void sound() { System.out.println("No sound!");

Potential Solutions Just leave it for the sub classes. – Have each sub class define sound() Define sound() in Animal as in the previous slide Sub classes override the method with more meaningful behavior as in the last example.

A better solution We know we want to be able to find the sound of objects that are instances of Animal The problem is we don’t know how to do that if all we know is its an Animal Make sound() an abstract method-Java Keyword public class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound();

Abstract method public class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound(); // We know we want it, but don’t know how, yet…

Abstract method Methods that are declared abstract have no body an undefined behavior. We can override this sound() method in the Cat and Square subclasses, and implement details

Abstract method contd. Now we know how to define the sound() class Cat extends Animal { Cat (String name) { super(name); } public void sound() { System.out.println(name+" Meowing!"); Now we know how to define the sound()

Abstract method contd. Now we know how to define the sound() class Bird extends Animal { Bird (String name) { super(name); } public void sound() { System.out.println(name+" Tweeting!"); Now we know how to define the sound()

Abstract method contd. sound() is now an abstract method in Animal what is wrong with the following code? Animal animal = new Animal(); System.out.println(animal.sound());

Abstract method contd. sound() is now an abstract method in Animal what is wrong with the following code? Animal animal = new Animal(); System.out.println(animal.sound()); Undefined behavior! BAD

Abstract class Not good to have undefined behaviors If a class has ONE or more abstract methods, the class must also be declared abstract. abstract class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound();

Abstract class what is wrong with the following code? abstract class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound(); what is wrong with the following code? Animal animal = new Animal();

Animal animal = new Animal(); Abstract class abstract class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound(); what is wrong with the following code? Animal animal = new Animal(); //Syntax error If a class is abstract, then we cannot create instances of that class

What is an abstract class? An abstract class is a class that is declared abstract. Important: Even if a class has zero abstract methods a programmer can still choose to make it abstract Abstract classes cannot be instantiated, but they can be sub classed.

Abstract class example public abstract class Animal { String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound();

Abstract class example contd. class Cat extends Animal { Cat (String name) { super(name); } public void sound() { System.out.println(name+" Meowing!");

Abstract class example contd. class Bird extends Animal { Bird (String name) { super(name); } public void sound() { System.out.println(name+" Tweeting!");

Abstract class example contd. class TestAnimal{ public static void main(String[] args) { Cat cat = new Cat("Bela"); cat.sound(); Bird bird = new Bird("Happy"); bird.sound(); //Animal animal = new Animal(); //animal.sound(); } } Output: Bela Meowing! Happy Tweeting!

Abstract class properties Abstract classes may or may not contain abstract methods If a class contains at least one abstract method, then the class must be declared abstract If a class is declared abstract, it cannot be instantiated To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Abstract class properties contd. If you don’t implement an abstract method (declared in the abstract class ) in the sub-class, then what will happen? public abstract class Animal{ String name; Animal(){} Animal(String name){ this.name = name; } public abstract void sound(); class Cat extends Animal { Cat (String name) { super(name);

Abstract class properties contd. If you don’t implement an abstract method (declared in the abstract class ) in the sub-class, then what will happen? class TestAnimal { public static void main(String[] args) { Cat cat = new Cat("Bela"); }

Abstract class properties contd. If you don’t implement an abstract method (declared in the abstract class ) in the sub-class, then what will happen? class TestAnimal { public static void main(String[] args) { Cat cat = new Cat("Bela"); //Error }

Week 10 Java Interfaces

Learning Outcomes At the end of this session, You will able to: Understand Java Interface; To Analyse how Interfaces and different then Abstract classes; Design and Implement Interfaces and Abstracts.

Lecture Outline Java Interface Interface vs Abstract final keyword in Java

What is an Interface? A Java Interface is just a definition of behaviour, similar to a Java abstract class (we will see their differences shortly) It is not a class but it is defined in a way similar to the class definition An Interface describes the functions and behaviors of a specific object type but doesn't implement them When a class implements an interface it has to implement all methods declared in that interface.

Java Interface Example Interface Animal // interface declaration public interface Animal { // constant public static final String type = "Mammal"; //abstract method public void sound (); }

Java Interface Example Cat implements Interface Animal class Cat implements Animal { private String name; Cat (String name) { this.name = name; } // class declaration public void sound () { System.out.println(name+" Meowing!"); }

Java Interface Example Bird implements Interface Animal class Bird implements Animal { private String name; Bird (String name) { this.name = name; } // class declaration public void sound () { System.out.println(name+" Tweeting!"); }

Java Interface Example class TestAnimal { public static void main (String[] args) { Animal animal1 = new Cat ("Bela"); Animal animal2 = new Bird ("Happy"); animal1.sound(); animal2.sound(); } Output: Bela Meowing! Happy Tweeting!

Abstract class vs. Interface

Interface Implementation interface MotorVehicle { void run(); int getFuel(); } // My team mate complies and writes vehicle looking that way class Car implements MotorVehicle int fuel; void run() print(“Running…………….."); int getFuel() return this.fuel;

Abstract Class abstract class MotorVehicle { int fuel; // They ALL have fuel, so lets implement this for everybody. int getFuel() return this.fuel; } // That can be very different, force them to provide their // own implementation. abstract void run(); // My teammate complies and writes vehicle looking that way class Car extends MotorVehicle void run() print(“Running………………");

final keyword in Java

final Variable Final variable is just like constant in C class FinalVariable { public static void main(String []args) { final double PI= Math.PI; //final integer variable //try to change value of PI PI= 4.14; System.out.println("Value of PI is: " + PI); } Error: cannot assign a value to final variable PI

final Method A final method can not be overridden class BaseClass { final public void display(){ System.out.println("I'm in Base class"); } class SubClass extends BaseClass public void display(){ System.out.println("I'm in Sub class"); Error: display()cannot override in BaseClass

final Class A final class can not be inherited final class BaseClass { public void display(){ System.out.println("I'm in Base class"); } class SubClass extends BaseClass public void display(){ System.out.println("I'm in Sub class"); Error: SubClass cannot inherit from final BaseClass

Reference Chapters 11&13, Introduction to Java Programming, Liang.