EXERCISES SOFTWARE DEVELOPMENT I. 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W
|
|
- Ursula Stevenson
- 5 years ago
- Views:
Transcription
1 EXERCISES SOFTWARE DEVELOPMENT I 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W
2 Inheritance
3 I INHERITANCE :: MOTIVATION Real world objects often exist in various, similar variants Attributes (size, weight, color) Behavior Etc. Objects are often grouped/arranged hierarchically Corporate structure (head department chief group leader employee) Means of transportation Transport Vehicle Train Boat Plane Truck Car InterCity Tram
4 I INHERITANCE :: MOTIVATION (2) Example Goals of inheritance public class Car { Date regdate; int color; float luggagespace; void drive () {... void opentrunk () {... Express commonalities Classification Specialization Re-use of code (this is only a positive side effect, not the main aim of inheritance!) public class Truck { Date regdate; int color; float loadingspace; void drive () {... void loading () {... Software Development I // 2018W // 4
5 I INHERITANCE :: MOTIVATION (3) Graphical view class Vehicle { Date regdate; int color; Superclass Parent class Base class Derived class Extended class Child class Subclass void drive () {... class Truck extends Vehicle { float loadingspace; Class Car extends Vehicle { float luggagespace; void loading () {... void opentrunk () {... Software Development I // 2018W // 5
6 INHERITANCE :: WHAT DOES IT STAND FOR? Inheritance is Declaration of new classes based on already existing classes New classes own ( inherit ) all attributes and functions/methods of the underlying base classes Source code of base class(es) can remain unchanged New/inherited class(es) can be extended with further attributes, additional methods Methods already defined in a base class can be changed in the inherited class Refinement = complement the functionality of the base class Replacement = replace/overwrite the original method/functionality Software Development I // 2018W // 6
7 INHERITANCE :: TERMS AND DEFINITIONS Every class in Java has one and only one direct superclass (concept of single inheritance) In the absence of any other explicit superclass (i.e., absence of keyword extends ), every class is implicitly a subclass of Object Object itself has no superclass Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class (i.e., Object); such a class is said to be descended from all the classes in the inheritance chain Superclass // base class versus Subclass (derived class) Base class = existing class Subclass = derived class Inheritance hierarchy Direct superclass Indirect superclass Root (class) Software Development I // 2018W // 7
8 INHERITANCE :: TERMS AND DEFINITIONS Implicit inheritance Every class in Java inherits all characteristics of the class Object Class Object defines some methods that are useful for all types of classes, e.g., equals(), clone(), etc. Software Development I // 2018W // 8
9 INHERITANCE :: TERMS AND DEFINITIONS Implicit inheritance (2) As the Object class sits at the top of the class hierarchy tree, every class is a descendant, direct or indirect, of this class. Every class you use or write inherits the instance methods of Object You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class Useful methods inherited from Object are protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object public boolean equals(object obj)indicates whether some other object is "equal to" this one protected void finalize() throws Throwable Called by the garbage collector on an object when garbage collection determines that there are no more references to the object public final Class getclass() Returns the runtime class of an object (static vs. dynamic type see Polymorphism) public int hashcode()returns a hash code value for the object public String tostring()returns a string representation of the object notify, notifyall, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program (not discussed here) Software Development I // 2018W // 9
10 I INHERITANCE :: INHERITANCE RELATION The Is-A Relation An object of a subclass is also an object of the superclass ( Is-A relation ) Example: superclass Vehicle, subclass Truck: A truck is a vehicle An object of the subclass can be used anywhere where an object of the superclass can be used (=substitution); inaccessibility of attributes In addition to the characteristics of the superclass, the declaration of the subclass adds new characteristics (attributes, methods) A subclass is always a specialization of the superclass Layers of abstraction hierarchy of classes A Vehicle B Car C Cabrio Software Development I // 2018W // 10
11 I INHERITANCE :: INHERITANCE RELATION Example: Is-A Relation between 'Car' and 'Vehicle public static void main (String[] args) { Car c = new Car(); Vehicle v; v=c; v.luggagespace = 3; v.regdate = new Date(); v.setdate(new Date()); c=v; //ok; a car ('c') 'Is-A' vehicle ('v ) //luggagespace (class Car) not accessible!! //ok; regdate defined in Vehicle! // not possible; not every vehicle is a car // Error: "Type mismatch: cannot convert from Vehicle to Car Software Development I // 2018W // 11
12 I INHERITANCE :: TERMS AND DEFINITIONS Explicit inheritance Using the keyword extends, a Java class can be extended subclass extend superclass, for example class Cabrio extends Car { // Car extended from Vehicle int foldingtoptime;... Class TwoSeatCabrio extends Cabrio { boolean auxilaryrearseats;... // Object Transport Vehicle Car Cabrio TwoSeatCabrio Instantiation TwoSeatCabrio car1 = new TwoSeatCabrio(); car1.color = "red"; // Instance variable of "Vehicle car1.foldingtoptime = 20; // Instance var. of "Cabrio car1.auxilaryrearseats = false; // Instance var. of "TwoSeatCabrio Software Development I // 2018W // 12
13 INHERITANCE :: JAVA SPECIFICS Inheritance in Java compared to other programming languages Java only allows single inheritance, i.e., the keyword extends is always followed by a single class name (the superclass) other programming languages such as C++ allow multiple inheritance, but not without imposing some problems (e.g., "diamond problem") Java only allows to declare subtypes of classes (Car Vehicle), but not to confine for example data types as compared to e.g. the XML scheme (xs:integer xs:short) what about this statement? public class SmallInteger extends Integer { Error: "The type SmallInteger cannot subclass the final class Integer see the definition of Integer: public final class Integer extends Number 'final' classes cannot be subclassed (i.e., extended)! Software Development I // 2018W // 13
14 I INHERITANCE IN JAVA :: EXAMPLE COMICCHARACTER public class ComicCharacter { private String name; void print() { System.out.println(name); void dance() { System.out.println(name + " dances."); void sing() { System.out.println(name + " sings."); String getname() { return name; void setname(string name) { this.name = name; Software Development I // 2018W // 14
15 I INHERITANCE IN JAVA :: EXAMPLE COMICCHARACTER (2) public class SuperHero extends ComicCharacter { // inherits characteristics from ComicCharacter ('print', 'dance', 'sing'), // adds the functionality to 'fight' private String superpower; void fight() { System.out.println (getname()+" fights."); String getsuperpower() { return superpower; void setsuperpower(string superpower) { this.superpower = superpower; public class Wizard extends ComicCharacter { // ComicCharacter behavior extended with the possibility to 'fly' void fly() { System.out.println(getName()+" flies."); Software Development I // 2018W // 15
16 I INHERITANCE IN JAVA :: EXAMPLE COMICCHARACTER (3) public static void main(string[] args) { ComicCharacter cc = new ComicCharacter(); cc.setname("gonzo"); cc.dance(); SuperHero sh = new SuperHero(); sh.setname("arnie"); sh.dance(); sh.fight(); Wizard wd = new Wizard(); wd.setname("john"); wd.sing(); wd.fly(); What about this call is it allowed? cc = new SuperHero(); cc.dance(); Gonzo dances. Arnie dances. Arnie fights. John sings. John flies. null dances. Software Development I // 2018W // 16
17 Polymorphism and Dynamic Binding
18 I POLYMORPHISM :: OBJECTS WITH DIFFERENT FORMS Polymorphism refers (in general) to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming (OOP) and the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. Demonstration of polymorphism with ComicCharacter Object of a subclass (SuperHero, Wizard) is-a object of the superclass (ComicCharacter) Objects of subclasses can be used instead of objects of the base class (see Vehicle Car example above!) Object variables might be polymorph (having different types ) Static data type (type of declaration) Dynamic data type (corresponds to the actual class affiliation at run time) Object of a subclass can be assigned to a variable of (declared, static) type of the parent class (multilevel!) Software Development I // 2018W // 18
19 I POLYMORPHISM :: EXAMPLE COMICCHARACTER Dynamic (runtime) type: SuperHero Static (declaration) type: ComicCharacter public static void main(string[] args) { ComicCharacter cc; cc = new SuperHero(); // A SuperHero "is-a" ComicCharacter cc.dance(); // Each ComicCharacter is able to dance cc.fight(); // A ComicCharacter can't fight! Attention! Polymorphism applies only to one direction public static void main(string[] args) { SuperHero sh; ComicCharacter cc; cc = new ComicCharacter(); sh = cc; // Not every ComicCharacter "is-a" // SuperHero! sh = new SuperHero(); // Other way round: ok (see above) cc = sh; Due to polymorphism, any object is assignable to a variable of type java.lang.object (but not the other way round!) To check the dynamic data type of a variable the instanceof operator can be used Software Development I // 2018W // 19
20 POLYMORPHISM :: THE "INSTANCEOF -OPERATOR The instanceof -operator checks at runtime the is-a relation of an objects' type in relation to a class, e.g. public static void main(string[] args) { SuperHero sh = new SuperHero(); System.out.println(sh instanceof SuperHero); // true System.out.println(sh instanceof ComicCharacter); // true System.out.println(sh instanceof Wizard); // false System.out.println(sh instanceof Object); // true Software Development I // 2018W // 20
21 I POLYMORPHISM :: EXAMPLE COMICCHARACTER public static void main(string[] args) { ComicCharacter cc; cc = new SuperHero(); // A SuperHero "is-a" ComicCharacter System.out.println(cc instanceof ComicCharacter); // true System.out.println(cc instanceof SuperHero); // true System.out.println(cc instanceof Object); // true cc.dance(); // Each ComicCharacter is able to dance cc.fight(); // A ComicCharacter can't fight! Exception in thread "main" java.lang.error:? Unresolved compilation problem: The method fight() is undefined for the type ComicCharacter Only attributes and methods of the superclass (ComicCharacter) are universally accessible! Software Development I // 2018W // 21
22 POLYMORPHISM :: EXAMPLE ARRAY OF VEHICLES Until now, arrays were declared with a single, fixed data type (int[], char[], ) An array of vehicles could only store instances of class Vehicle Vehicle[] veh = new Vehicle[10]; With inheritance and polymorphism it is now possible to store different vehicle objects in that array (classes Motorbike, Car, Truck are extensions of class Vehicle): Vehicle[] veh = new Vehicle[10]; // heterogenous array veh[0] = new Vehicle(); // assignment as usual veh[1] = new Truck(); // assignment of a truck object veh[2] = new Car(); // assignment of a car object veh[3] = new Motorbike(); // assignment of a motorbike In each of the array elements are by default only attributes/methods of the base class (Vehicle) accessible! If, for example, class Motorbike defines a method performwheelie() (that is not defined in class Vehicle), then the following method call would be illegal! veh[3].performwheelie(); // not accessible ((Motorbike)veh[3]).performWheelie(); // ok with typecast ((Motorbike)veh[2]).performWheelie(); // runtime error! Software Development I // 2018W // 22
23 I INHERITANCE :: METHOD REPLACEMENT/ REFINEMENT Method replacement A method defined (and implemented) in the base class is fully replaced by another method in the subclass class Smurf extends ComicCharacter { private String color; void Smurf() { color = "Blue"; void sing() { System.out.println(color + " Smurfs don't sing!"); Method replacement can be prohibited (restricted) if the method in the parent class is defined as final (keyword before method name) Software Development I // 2018W // 23
24 I INHERITANCE :: METHOD REPLACEMENT/ REFINEMENT (2) Method refinement Complementing/extending the method body of a method already defined in the parent class In the subclass 1. Invoke the overridden method from the superclass through the use of the keyword "super" 2. Add additional statements Example: class Smurf extends ComicCharacter { super.dance() invokes the (overriden) dance() method from the superclass void dance() { ComicCharacter super.dance(); System.out.println("The other Smurfs applaud"); (Although discouraged, "super" can also be used to refer to a hidden field ) Software Development I // 2018W // 24
25 DYNAMIC BINDING :: INTRODUCTION + doit () Suppose you have 3 Java classes: A, B, and C where class B extends A and class C extends B (class inheritance hierarchy: A on top, then B in the middle, and finally C on the bottom); all 3 classes implement the instance method void doit(); public static void main(string[] args) { A x = new A(); x.doit(); // doit() from A A y = new B(); y.doit(); // doit() from??? What version of the y.doit() method is actually executed and why? C Given the class structure, the question is which version of the doit() method will be executed the one in class A, B, or C? + doit () Var. y is an object of type A, but it is instantiated as an object of class B The version of the doit() method that s executed by the object y is the one in class B because of what is known as dynamic binding in Java. Dynamic binding basically means that the method implementation that is actually called is determined at run time, and not at compile time. Dynamic binding (also known as late binding): the method that will be run is chosen at run time. A B + doit () Software Development I // 2018W // 25
26 I DYNAMIC BINDING :: EXAMPLE COMICCHARACTER Method that will be called is determined at run time (depending on dynamic type of the object) public static void main(string[] args) { ComicCharacter cc = new ComicCharacter(); cc.setname("papasmurf"); cc.sing(); sm = new Smurf(); sm.sing(); cc = sm; cc.sing(); // sing() method of class ComicCharacter // sing() method of class Smurf; different // behavior (method replaced in class Smurf) // cc is of (static) type ComicCharacter; // sing() method of class Smurf!! cc = new SuperHero(); cc.sing(); // sing() method of class SuperHero; the // method is not overridden in that class, // i.e. the sing method of the superclass // ComicCharacter is invoked Papasmurf sings. Blue Smurfs don't sing! null sings. Software Development I // 2018W // 26
27 I ABSTRACT CLASSES AND INTERFACES :: DECLARATION W/O IMPLEMENTATION An abstract method is a method declared without an implementation, i.e., with only a signature and no implementation body (no {-braces) - like this: public abstract void draw(int x, int y); An abstract class is a class that is declared abstract It may or may not include abstract methods Abstract classes cannot be instantiated, but they can be subclassed when an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract (and implementation of the remaining methods must be provided in further subclasses) If a class includes at least one abstract method, the class itself must be declared abstract Abstract class interface! (see the following examples) unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation if an abstract class contains only abstract method declarations, it should be declared as an interface instead Software Development I // 2018W // 27
28 ABSTRACT CLASSES :: EXAMPLE 'GEOMETRICFIGURES (1) Case 1: Abstract class/methods abstract class GeometricFigure { abstract public double area(); public void printarea() { System.out.print("Area: "+ this.area()); Abstract class may contain methods with implementation, but at least one abstract method... class Circle extends GeometricFigure { double radius; public Circle (double radius) { super(); this.radius = radius; public double area() { return Math.PI * radius * radius; A nonabstract class has to provide an implementation for all the abstract methods in the superclass. Concrete methods might be overridden or extended. public void printarea() { super.printarea(); System.out.println(" (Circle)"); Software Development I // 2018W // 28
29 ABSTRACT CLASSES :: EXAMPLE 'GEOMETRICFIGURES (2A) Case 1: Abstract class/methods class Square extends GeometricFigure { double len; public Square(double len) { this.len = len; public double area() { return len*len; If not overridden, method printarea() from the super class GeometricFigure will be used! Area: (Circle) Area: 25.0 // public void printarea() { // super.printarea(); // System.out.println(" (Square)"); // public static void main(string[] args) { GeometricFigure [] figures = new GeometricFigure[2]; figures[0] = new Circle (5); figures[1] = new Square (5); figures[0].printarea(); figures[1].printarea(); Software Development I // 2018W // 29 Basic instantiation): - Circle c = new Circle(5); - c.printarea(); - Square sq = new Square(5); - sq.printarea(); Dynamic binding: Method printarea() that will be called is determined at run time (depending on dynamic type)
30 ABSTRACT CLASSES :: EXAMPLE 'GEOMETRICFIGURES (2A) Case 1: Abstract class/methods class Square extends GeometricFigure { double len; public Square(double len) { this.len = len; Area: (Circle) Area: 25.0 public double area() { return len*len; // public void printarea() { // super.printarea(); // System.out.println(" (Square)"); // public static void main(string[] args) { GeometricFigure [] figures = new GeometricFigure[2]; figures[0] = new Circle (5); figures[1] = new Square (5); figures[0].printarea(); figures[1].printarea(); Software Development I // 2018W // 30 Dynamic binding: Method printarea() that will be called is determined at run time (depending on dynamic type)
31 INTERFACES :: EXAMPLE 'GEOMETRICFIGURES (1) Interface Definition and Implementation interface GeometricFigure { // constant declarations, if any public class Circle implements GeometricFigure { double radius; public double area(); public void printarea(); Method declarations: Method signatures have no {-braces and are terminated with a semicolon. A nonabstract class has to provide an implementation for all method signatures specified in the interface. public Circle (double radius) { super(); this.radius = radius; public double area() { return Math.PI * radius * radius; public void printarea() { System.out.println("Area: "+ this.area() + Software Development I // 2018W // 31
32 INTERFACES :: EXAMPLE 'GEOMETRICFIGURES (2) Provide an Implementation for Square and instantiate a Circle and a Square and run the printarea Method on both. interface GeometricFigure { public double area(); public void printarea(); public static void main(string[] args) { GeometricFigure [] figures = new GeometricFigure[ figures[0] = new Circle (5); figures[1] = new Square (5); class Circle implements GeometricFigure { double radius; public Circle (double radius) { super(); this.radius = radius; public double area() { return Math.PI * radius * radius; figures[0].printarea(); figures[1].printarea(); public void printarea() { System.out.println("Area: "+ this.area() + " (Circle)"); Software Development I // 2018W // 32
33 INTERFACES :: EXAMPLE 'GEOMETRICFIGURES (3) Provide an Implementation for Square and instantiate a Circle and a Square and run the printarea Method on both. class Square implements GeometricFigure { double len; public Square(double len) { this.len = len; public double area() { return len*len; public static void main(string[] args) { GeometricFigure [] figures = new GeometricFigure[ figures[0] = new Circle (5); figures[1] = new Square (5); figures[0].printarea(); figures[1].printarea(); public void printarea() { System.out.println("Area: "+ this.area() + " (Square)"); Software Development I // 2018W // 33
34 INTERFACES :: EXAMPLE 'GEOMETRICFIGURES (4) Provide an Implementation for Square and instantiate a Circle and a Square and run the printarea Method on both. interface GeometricFigure { public double area(); public void printarea(); public static void main(string[] args) { GeometricFigure [] figures = new GeometricFigure[ figures[0] = new Circle (5); figures[1] = new Square (5); class Square implements GeometricFigure { double len; public Square(double len) { this.len = len; public double area() { return len*len; figures[0].printarea(); figures[1].printarea(); public void printarea() { System.out.println("Area: "+ this.area() + " (Square)"); Software Development I // 2018W // 34
35 INTERFACES :: EXAMPLE 'GEOMETRICFIGURES Provide an Implementation for Square and instantiate a Circle and a Square and run the printarea Method on both. interface GeometricFigure { // constant declarations, if any class Square implements GeometricFigure { double len; public double area(); public void printarea(); public Square(double len) { this.len = len; class Circle implements GeometricFigure { double radius; public Circle (double radius) { super(); this.radius = radius; public double area() { return len*len; public void printarea() { System.out.println("Area: "+ this.area() + " (Square)"); public double area() { return Math.PI * radius * radius; public void printarea() { System.out.println("Area: "+ this.area() + " (Circle)"); public static void main(string[] args) { GeometricFigure [] figures = new GeometricFigure[2]; figures[0] = new Circle (5); figures[1] = new Square (5); figures[0].printarea(); figures[1].printarea(); Software Development I // 2018W // 35
36 INTERFACES: EXAMPLE 'GEOMETRICFIGURES (5) Summary (incl. dynamic binding) // TESTS (Abstract class): // 1. Not allowed (error: "cannot instantiate the type GeometricFigure") GeometricFigure gf = new GeometricFigure(); // 2. Allowed; Square/Circle "is-a" GeometricFigure Circle c = new Circle(5); GeometricFigure gf = new Square(5); // also allowed: new Circle(5); // 3. Calls the printarea()-method of Square-class c.printarea(); gf.printarea(); // printarea()-method selected with concept of dynamic binding! // TESTS (Interface): // 1. Not allowed (error: "cannot instantiate the type GeometricFigure") GeometricFigure gf = new GeometricFigure(); // 2. Allowed; Square/Circle "is-a" GeometricFigure Square sq = new Square(5); GeometricFigure gf = new Circle(5); // also allowed: new Square(5); // 3. Calls the printarea()-method of Circle-class sq.printarea(); gf.printarea(); // printarea()-method selected with concept of dynamic binding! Software Development I // 2018W // 36
37 EXERCISES SOFTWARE DEVELOPMENT I 09 Objects: Inheritance, Polymorphism and Dynamic Binding 2018W
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 informationWhat 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 informationInheritance. The Java Platform Class Hierarchy
Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those
More informationArgument 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 informationINHERITANCE. 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 informationInheritance 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 informationInheritance. 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 informationCS5000: 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 informationCS-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 informationJAVA 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 information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationOBJECT 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 informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationHAS-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 informationJava Magistère BFA
Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt
More informationDay 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 informationPolymorphism 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 informationInheritance (continued) Inheritance
Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses
More informationProgramming 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 informationChapter 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 informationJava 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 informationIntroduction to Inheritance
Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits
More informationFirst 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 informationMore 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 informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationAbstract Classes and Interfaces
Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass
More information(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )
(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) Dongwon Jeong djeong@kunsan.ac.kr; http://ist.kunsan.ac.kr/ Information Sciences and Technology Laboratory, Dept. of
More informationAbstract 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 informationCSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level
CSE1720 Click to edit Master Week text 08, styles Lecture 13 Second level Third level Fourth level Fifth level Winter 2014! Thursday, Feb 27, 2014 1 General Info Continuation of Chapter 9 Read Chapter
More informationChapter 10 Classes Continued. Fundamentals of Java
Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationOutline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.
Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not
More informationJava 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 informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationChapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber
Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the
More informationSubclasses, 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 informationJava 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 informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
More informationMore 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 informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationClass definition. complete definition. public public class abstract no instance can be created final class cannot be extended
JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can
More informationPieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017
Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL Inheritance and February 10, 2017 1/45 Topics
More informationLecture 4: Extending Classes. Concept
Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract
More informationObject 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 informationHAS-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 informationObject Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia
Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing
More informationJava 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 informationWhat 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 informationPieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018
Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Java Inheritance Example I Visibility peekabo Constructors Fontys Hogeschool voor Techniek en Logistiek January 11, 2018
More informationExercise: 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 informationCOMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed
1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every
More informationInheritance and Polymorphism
Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html
More informationName 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 informationJava. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)
Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu
More informationLecture 2: Java & Javadoc
Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block
More informationAnnouncement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August
Polymorphism, Dynamic Binding and Interface 2 4 pm Thursday 7/31/2008 @JD2211 1 Announcement Next week is off The class will continue on Tuesday, 12 th August 2 Agenda Review Inheritance Abstract Array
More informationClass, Variable, Constructor, Object, Method Questions
Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx
More informationCLASS DESIGN. Objectives MODULE 4
MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors
More informationChapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,
Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design
More informationJava: introduction to object-oriented features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More informationMethods Common to all Classes
Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;
More informationCSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community
CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring
More informationCSE 143 Lecture 20. Circle
CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public
More informationINHERITANCE & 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 informationChapter 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 informationCOMP200 - Object Oriented Programming: Test One Duration - 60 minutes
COMP200 - Object Oriented Programming: Test One Duration - 60 minutes Study the following class and answer the questions that follow: package shapes3d; public class Circular3DShape { private double radius;
More informationASSIGNMENT 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 informationCPS 506 Comparative Programming Languages. Programming Language
CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support
More informationMore On inheritance. What you can do in subclass regarding methods:
More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature
More informationCSC 1214: Object-Oriented Programming
CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:
More informationCISC370: Inheritance
CISC370: Inheritance Sara Sprenkle 1 Questions? Review Assignment 0 due Submissions CPM Accounts Sara Sprenkle - CISC370 2 1 Quiz! Sara Sprenkle - CISC370 3 Inheritance Build new classes based on existing
More informationModern Programming Languages. Lecture Java Programming Language. An Introduction
Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationLecture Notes Chapter #9_b Inheritance & Polymorphism
Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1
More informationLecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting
Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006
More informationInheritance -- 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 informationChapter 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 informationBinghamton University. CS-140 Fall Dynamic Types
Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected
More informationObject 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 informationProgramming in the Large II: Objects and Classes (Part 2)
Programming in the Large II: Objects and Classes (Part 2) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen
More informationChapter 9 Inheritance
Chapter 9 Inheritance I. Scott MacKenzie 1 Outline 2 1 What is Inheritance? Like parent/child relationships in life In Java, all classes except Object are child classes A child class inherits the attributes
More informationPolymorphism. return a.doublevalue() + b.doublevalue();
Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces
More informationMaking New instances of Classes
Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using
More informationPolymorphism and Interfaces. CGS 3416 Spring 2018
Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that
More informationCS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and
More informationThe Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000
The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes
More informationExample: 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 informationCS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)
CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers
More informationCMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.
CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object
More informationObject Oriented Programming: Based on slides from Skrien Chapter 2
Object Oriented Programming: A Review Based on slides from Skrien Chapter 2 Object-Oriented Programming (OOP) Solution expressed as a set of communicating objects An object encapsulates the behavior and
More information24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini
24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance
More informationInheritance, Polymorphism, and Interfaces
Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)
More informationIntroducing Java. Introducing Java. Abstract Classes, Interfaces and Enhancement of Polymorphism. Abstract Classes
Abstract Classes, and Enhancement of Polymorphism Abstract Classes Designing a hierarchy, it s current (and proper) practice placing in the super-classes all the common methods and data structures required
More informationIST311. Advanced Issues in OOP: Inheritance and Polymorphism
IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition
More informationInheritance 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 informationThe Essence of OOP using Java, Nested Top-Level Classes. Preface
The Essence of OOP using Java, Nested Top-Level Classes Baldwin explains nested top-level classes, and illustrates a very useful polymorphic structure where nested classes extend the enclosing class and
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 17 Inheritance Overview Problem: Can we create bigger classes from smaller ones without having to repeat information? Subclasses: a class inherits
More information