Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

Similar documents
Systems programming. Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

Object Oriented Java

Lecture 4: Extending Classes. Concept

ECE 122. Engineering Problem Solving with Java

Inheritance and Polymorphism

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

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

What is Inheritance?

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

Chapter 5. Inheritance

Class, Variable, Constructor, Object, Method Questions

CS-202 Introduction to Object Oriented Programming

Chapter 5 Object-Oriented Programming

Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

Java: introduction to object-oriented features

Inheritance (Part 5) Odds and ends

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

Inheritance. Transitivity

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

Inheritance -- Introduction

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

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Programming overview

Java Fundamentals (II)

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

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

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Informatik II (D-ITET) Tutorial 6

Week 5-1: ADT Design

CS260 Intro to Java & Android 03.Java Language Basics

Declarations and Access Control SCJP tips

Inheritance Motivation

Computer Science II (20073) Week 1: Review and Inheritance

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Java Object Oriented Design. CSC207 Fall 2014

CMSC 132: Object-Oriented Programming II

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

COP 3330 Final Exam Review

CS1150 Principles of Computer Science Objects and Classes

Informatik II Tutorial 6. Subho Shankar Basu

Introduction to Inheritance

INHERITANCE AND EXTENDING CLASSES

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

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

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

1 Shyam sir JAVA Notes

Object-Oriented Concepts

CMSC 132: Object-Oriented Programming II. Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

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

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

C08: Inheritance and Polymorphism

CMSC 132: Object-Oriented Programming II

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

C08: Inheritance and Polymorphism

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

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

What are the characteristics of Object Oriented programming language?

Comp 249 Programming Methodology

Inheritance and Substitution (Budd chapter 8, 10)

More On inheritance. What you can do in subclass regarding methods:

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

Inheritance (continued) Inheritance

Building custom components IAT351

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

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

Arrays Classes & Methods, Inheritance

Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Big software. code reuse: The practice of writing program code once and using it in many contexts.

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

Chapter 6 Introduction to Defining Classes

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Introduction to Programming Using Java (98-388)

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

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

Java Magistère BFA

Chapter 10 Classes Continued. Fundamentals of Java

Basic Object-Oriented Concepts. 5-Oct-17

Polymorphism and Inheritance

JAVA OBJECT-ORIENTED PROGRAMMING

CISC370: Inheritance

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

Full file at Chapter 2 - Inheritance and Exception Handling

Object Orientated Programming Details COMP360

Object Oriented Programming. Java-Lecture 11 Polymorphism

ECE 122. Engineering Problem Solving with Java

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

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

Object-Oriented Programming (Java)

SSE3052: Embedded Systems Practice

Exercise: Singleton 1

COMP 110/L Lecture 19. Kyle Dewey

Transcription:

Systems programming Object Oriented Programming I. Object Based Programming II. Object Oriented Programming Telematics Engineering M. Carmen Fernández Panadero <mcfp@it.uc3m.es> mcfp@it.uc3m.es 2010 1

Scenario V: Reusing code. Inheritance Once you are able to create your own classes, you are ready to work in teams and reuse code developed by your colleagues. Your team will provide you with a set of classes and you are required to create specializations or generalizations of them. Objective: Be able to create a derived class adding some characteristics (attributes) and behavior (methods) to an existing class. Be able to extract all the common code from a set of similar classes in order to group it into a new parent class so that it is easier to maintain. Be able to create objects, and reference and access their attributes and methods, depending on their position in the inheritance hierarchy and their modifiers. Work plan: Memorize the nomenclature related to inheritance Memorize the java syntax related to inheritance (extends) and to reference (super, this) and access (modifiers) to the different members. Know basic inheritance mechanisms, such as attribute hiding, overriding of methods and overloading of constructors, and know what they are used for and how they are used. mcfp@it.uc3m.es 2010 Review 2

Contents Basic inheritance concepts Inheritance hierarchy Overriding I: Attribute Hiding Overriding II: Method Overriding Constructors of derived classes Static and Final Modifiers Scope and access mcfp@it.uc3m.es 2010 3

Inheritance What is it? Mechanism for software reuse Allows to define from a class other related classes that can be a: Specialization of the given class. (Eg Car class is a specialization of the class Vehicle ) Scenario: We have to implement a new class that is very similar to a previous one but it needs aditional information (characteristics and behaviour) Solution: Create a class derived from the old one and add it new functionality without having to rewrite the common code Generalization of the given class. (The Vehicle class is a generalization of the Car class). Scenario : We have a set of similar classes with code that is repeated in every class and thus difficult to update and maintain (eg. a letter should be added to the serial number) Solution : We move the code that is repeated to a single site (the parent class) mcfp@it.uc3m.es 2010 4

Inheritance What is it? Resouce name description getname() getdescription() Resource name description getname() getdescription() Classroom name description location getname() getdescription() getlocation() computer name description operatingsystem getname() getdescription() getos() Classroom location getlocation() Computer operatingsistem getos() public class Classroom extends Resource public class Computer extends Resource The attributes and methods that appear in blue in the parent class are repeated in the subclasses. (Left picture) It is not necessary to repeat the code, you only have to say that a class extends the other or inherits from it. (Right picture) mcfp@it.uc3m.es 2010 5

Inheritance Nomenclature If we define the class car from the class vehicle, it is said that: car" inherits attributes and methods from "vehicle car" extends "vehicle" car" is a subclass of "vehicle" Derived class Child class vehicle" is a superclass of car" Base class Parent class Inheritance implements the is-a relation A car is-a vehicle; a dog is-a mammal, etc. mcfp@it.uc3m.es 2010 6

Inheritance Declaration of subclasses The syntax for declaring subclasses is: class Subclass extends Superclass {... Student Person Employee class Person {... class Student extends Person {... class Employee extends Person {... class Professor extends Employee {... class Secretary extends Employee {... Professor Secretary Nati, mcfp@it.uc3m.es 2010 7

Inheritance Subclass Attributes Methods firstname print lastname yearbirth Inherited from class Person group timetable setgroup printgroup Class Student Nati, mcfp@it.uc3m.es 2010 8

Inheritance How is it used? Eg.: Person.java public class Person { protected String firstname; protected String lastname; protected int yearbirth; public Person () { public Person (String firstname, String lastname, int yearbirth){ this.firstname = firstname; this.lastname = lastname; this.yearbirth = yearbirth; public void print(){ System.out.print("Personal data: " + firstname + " " + lastname + " ( + yearbirth + ")"); Nati, mcfp@it.uc3m.es 2010 9

Inheritance How is it used? Eg.: Person.java public class Student extends Person { protected String group; protected char timetable; public Student() { public Student(String firstname, String lastname, int birthyear) { super(firstname, lastname, birthyear); public void setgroup(string group, char timetable) throws Exception { if (group == null group.length() == 0) throw new Exception ("Invalid group"); if (timetable!= 'M' && timetable!= 'A') throw new Exception ("Invalid timetable"); this.group = group; this.timetable = timetable; public void printgroup(){ System.out.print(" Group " + group + timetable); Nati, mcfp@it.uc3m.es 2010 10 10

Inheritance How is it used? Eg.: Test.java public class Test { public static void main (String[] args) throws Exception{ Person neighbor = new Person ("Luisa", "Asenjo Martínez", 1978); Student astudent = new Student ("Juan", "Ugarte López", 1985); astudent.setgroup("66", 'M'); neighbor.print(); System.out.println(); astudent.print(); astudent.printgroup(); Nati, mcfp@it.uc3m.es 2010 11

Inheritance Consequences of extension of classes Inheritance of the interface The public part of the suclass contains the public part of the superclass The Student class contains the method print() Inheritance of the implementation The implementation of the subclass contains the implementation of the superclass When calling the method of the superclass on an object of the subclass (astudent.print()) the expected behavior takes place Nati, mcfp@it.uc3m.es 2010 12

Inheritance Inheritance hierarchy in Java In Java, all classes are related through a single inheritance hierachy A class can: Explicitly inherit from another class, or Implicitly inherit from the class Object (defined in the Java core) This is the case both for predefined classes and for user-defined classes mcfp@it.uc3m.es 2010 13

Inheritance hierarchy Object Boolean Character Number Person Integer Long Float Double Student Employee Secretary Professor nati@it.uc3m.es 2010 14

Inheritance Overriding Modification of the elements of the base class inside the derived class The derived class can define: An attribute with the same name as one of the base class attribute hiding A method with the same signature as one of the base class Method overriding The second case is more usual Nati, mcfp@it.uc3m.es 2010 15

Granny class Overriding I (Shadowing) Attribute hiding Transport String name = ground" Parent class convoy vehicle String name = car" Child class scooter car How can I access to hiding variables? name (car name) this.name (car name) super.name (vehicle name) ((vehicle)this).name (vehicle name) super.super.name (bad) ((transport)this).name (transport name) String name = "Ferrari" variables Child class: visibles Variables Parent class hidden mcfp@it.uc3m.es 2010 16

Overriding I (Shadowing) Attribute hiding Attributes Methods Student a = new Student(...); System.out.println(a.firstName); firstname lastname yearbirth print() Person p = a; System.out.println(p.firstName); Inherited from class Person firstname group setgroup(string s) printgroup() timetable Class Student Nati@it.uc3m.es 2010 17

Overriding I (Shadowing) Attribute hiding When accessing an attribute, the type of the reference is used for deciding which value to access The attribute of the subclass needs to have the same name as the one of the superclass But not necessarily the same type Not very useful in practice Allows the superclasses to define new attributes without affecting the subclasse mcfp@it.uc3m.es 2010 18

Overriding I (Shadowing) Attribute hiding. Example class SuperShow { public String str = "SuperStr"; class ExtendShow extends SuperShow { public int str = 7; { class Show { public static void main (String[] args) ExtendShow ext = new ExtendShow(); SuperShow sup = ext; prints SuperStr System.out.println(sup.str); System.out.println(ext.str); prints 7 Nati, mcfp@it.uc3m.es 2010 19

Overriding I (Shadowing) Attribute hiding If we define an attribute (variable) in a subclass with the same name and type that other one in the superclass. Variable in the superclass remains hidden. We can access one variable or the other using this and super. Eg: Car" extends from Vehicle" and Vehicle" extends from Transport. We define the variable String name in the three classes. How can we know if we are referring to the name of transport, the name of the vehicle or the name of the car? mcfp@it.uc3m.es 2010 20

Overriding II Method overriding. What is it? If the subclass defines a method with the same signature (name + number and type of the parameters) the method in the superclass is hidden. If the final modifier is userd in a method, this method can not be overriden How can we access hidden methods?: start() (run the start method of the car ) this.start() (run the start method of the car ) super.start() (run the start method of the vehicle ) super.super.start() (Bad) Methods of the child class: visible Methods of the parent class: hidden mcfp@it.uc3m.es 2010 21

Overriding II Method overriding. What is it? Resource name Description getname() getdescription() Resource name description getname() getdescription() Classroom name description localization getname() getdescriptoin() getlocalization() Computer name description OperatingSystem getname() getdescription() getos() Classroom description localization getlocalization() getdescription() Computer OperatingSystem getos() this.getdescription() public class Classroom extends Resource public class Computer extends Resource super.getdescripcion mcfp@it.uc3m.es 2010 22

Overriding II Method overriding. Object error no method(parameters)? no Another ancestor method(parameters)? no Superclass method(parameters)? message object instance Subclass no method(parameters)? method(parameters) Nati, mcfp@it.uc3m.es 2010 23

Overriding II Method overriding. When sending a message to an object, the selected method: It depends on the class which the object is an instance of It does not depend on the reference class to which it is assigned, as in the case of attributes Nati, mcfp @it.uc3m.es 2010 24

Overriding II Method overriding. Example class SuperShow { public String str = "SuperStr"; public void show() { System.out.println("Super.show: " + str); class ExtendShow extends SuperShow { public String str = "ExtendStr"; public void show() { System.out.println("Extend.show: " + str); class Show2 { public static void main (String[] args) { ExtendShow ext = new ExtendShow(); SuperShow sup = ext; sup.show(); ext.show(); Both print: Extend.show: ExtendStr Nati, mcfp@it.uc3m.es 2010 25

Overriding II Final methods Method overriding is useful for Extending the functionality of a method Particularizing the functionality of a method to the derived class If it is not desired that subclasses are able to modify a method or an attribute of the base class, the reserved word final should be applied to the method or attribute mcfp@it.uc3m.es 2010 26

this and super references this references to the current class object super references the current object casted as if it was an instance of its superclass With the super reference, the methods of the base class can be explicitly accessed super is useful when overriding methods public class Student extends Person { // the rest remains the same public void print(){ super.print(); System.out.print("Group:" + group+ schedule); Nati, mcfp@it.uc3m.es 2010 27

Overriding vs. overloading Overriding: The subclass substitutes the implementation of a method of the superclass Both methods need to have the same signature Overloading: There is more than one method with the same name but different signature The overloaded methods can be declared in the same class or in different classes in the inheritance hierarchy nati, mcfp@it.uc3m.es 2010 28

Constructors and inheritance To create an object, the following steps are done: 1. The base part is created 2. The derived part is added If the base class of the object inherits from another class, step 1 is applied in the orden of the inheritance chain, until we reach Object For example, when creating a Student object, that extends Person, the steps would be: 1. The part corresponding to Person is created. To do so: 1. The part corresponding to Object is created. 2. The Person elements are added 2. The Student elements are added nati@it.uc3m.es 2010 29

Constructors and inheritance A call to the constructor of the base class is always done in the constructor of the derived class. This is the first action of the constructor (always in the first line) Two possibilities: Not explicitly indicate it Explicitly indicate it (mandatory in the first line) mcfp@it.uc3m.es 2010 30

Constructors and inheritance 1.If it is not explicit, Java automatically inserts a call to super() in the first line of the constructor of the derived class. public Student (String firstname, String lastname, int yearbirth, String group, char timetable) { // Java inserts here a call to super() this.firstname = firstname; this.lastname = lastname; this.yearbirth = yearbirth; this.group = group; this.timetable = timetable; Nati, mcfp@it.uc3m.es 2010 31

Constructors and inheritance 2. Explicitly coded public Student (String firstname, String lastname, int birthyear, String group, char timetable) { super(firstname, lastname, birthyear); this.group = group; this.timetable = timetable; Nati, mcfp@it.uc3m.es 2010 32

Modifiers and access Final The final modifier can be applied to: Parameters: Means that the value of such parameter cannot be changed inside the method public void mymethod(final int p1, int p2){ //p1 value cannot be changed Methods: Means that it cannot be overridden in derived classes public final void mymethod(){ //mymethod cannot be overridden Classes: Avoid extending the class. It cannot be inherited. public final class myclass(){ //myclass cannot be extended Nati, mcfp, @it.uc3m.es 2010 33

Modifiers and access Static (static members) static modifier Static members exist only once per class, independently of the number of instances (objects) of the class that have been created or even if none (instances) exists. Static members can be accessed using the class name. An static method cannot access non-static members directly, it must first create an object. Mcfp, rcrespo@it.uc3m.es 2010 34

Modifiers and access Static. Some rules Static members are invoked with: ClassName.staticMethod(); ClassName.staticAttribute; Non static members require an instance (object) in order to be accessed. ClassName objectname = new ClassName(); Non static members are invoked with: objectname.normalmethod(); objectname.normalattribute; When a static member is invoked (called) from inside the same class, the class name can be deleted. I.e. it can be written: staticmethod(); staticattribute; instead of: ClassName.staticMethod(); ClassName.staticAttribute; Mcfp, rcrespo@it.uc3m.es 2010 35

access others MODIFIERS class method attribute public (friendly) protected private abstract final static Applied to inner classes Cannot be instantiated For inheriting from them At least 1 abstract method Cannot be extended. It is a leave in the inheritance tree. Accesible to any other class Accessible only to classes in the same package Accessible to the class and its subclasses Accessible only inside the class Has no code It is implemented in the subclasses or child classes Cannot be overridden. It is constant and cannot be modified in the child classes. Its value cannot be changed, it is constant. It is normally used together with static. Maximum level class. It is the same for all of It is the same for all of the Applied to inner classes the class objects. class objects. Use: copyright Java: Estructura del lenguaje 36 Mcfp, rcrespo@it.uc3m.es mcfp@it.uc3m.es2010 ClassName.method (); 36 (*) http://www.coderanch.com/t/527185/java/java/understanding-modifiers-classes