CSC 143 Inheritance.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

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.
OOP: Inheritance By: Lamiaa Said.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
2009 first semister Instructor: Abdalrahman Obidat 1 Revision 3 Instructor: Abdalrahman Obidat.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Chapter 10 Inheritance and Polymorphism
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance and Access Control CS 162 (Summer 2009)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance Inheritance is the process of extending the functionality of a class by defining a new class that inherit,all the features of extending class.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance.
Modern Programming Tools And Techniques-I
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Abstract classes and interfaces
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Inheritance in Java.
Road Map Inheritance Class hierarchy Overriding methods Constructors
Week 8 Lecture -3 Inheritance and Polymorphism
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
CS240: Advanced Programming Concepts
Instructor: Abdalrahman Obidat
Chapter 9 Inheritance and Polymorphism
Inheritance Basics Programming with Inheritance
Abstract classes and interfaces
Comp 249 Programming Methodology
Java Programming Language
Advanced Java Topics Chapter 9
Computer Programming with JAVA
Java – Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Java Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 14 Abstract Classes and Interfaces
Abstract classes and interfaces
Chapter 11 Inheritance and Polymorphism
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
C++ Object Oriented 1.
CIS 110: Introduction to computer programming
Programming in C# CHAPTER 5 & 6
Presentation transcript:

CSC 143 Inheritance

Introduction Classes have proven very useful They help us write programs the way we view the world: interface vs implementation There is more to come! Java supports object oriented programming, i.e., Inheritance (sub classing) Dynamic dispatch (polymorphism) Two very powerful programming tools! They help us write less code

Composition: has-a relationship We have used many times several classes together, e.g., Use an instance of a class as an instance field of another class public class Landscape { private Mountain m = new Mountain(); } This a "has-a" relationship A Landscape "has-a" Mountain Also called aggregation

Organization hierarchy Often, we classify things according to a hierarchy (from general to specific), e.g. part of the organization of a university UniversityMember Staff Faculty Lecturer Professor Student Freshman Sophomore

Inheritance: is-a relationship Objects have also an "is-a" relationship A Freshman "is-a" Student , a Lecturer "is-a" UniversityMember Java gives us the tools to implement an "is-a" relation. We can map our view of the world on the computer

Inheritance in Java Inheritance is a way to encode the "is-a" relation in OO languages Freshman declares that it "is-a" Student by inheriting from it A derived class inherits from a base class by writing "extends BaseClassName" in the derived class declaration base class (or superclass) derived class (or subclass) public class Freshman extends Student { /* Freshman-specific stuff here */}

What is inherited? (1) The subclass inherits all of the public or protected or private members(data+methods) of its superclass (= everything but constructors) Members declared public or protected within the superclass can be used by the subclass as if they were declared within the subclass itself. protected member of a class: visible within the class itself, the package of the class, and the subclasses (even if they are in a different package). More on protected later.

What is inherited? (2) private members of the superclass are unavailable outside the superclass scope. package level members of the superclass are unavailable outside the package scope. If the superclass and subclass are in the same package, the subclass can access any package level members of the superclass A subclass instance is also a superclass instance (is-a relation). All methods of the superclass can be used on a subclass instance.

Scope example Base.java Derived.java package org.seattlecentral; public class Base { public int i; //visible everywhere int j;//visible within the package protected int k; //visible within // the package and any derived class private int l;// visible within Base only } Derived.java import edu.seattlecentral.Base; public class Derived extends Base{ public void update(){ i=4; // OK j=5; //Error, not in the same package k=6; // OK l=7; /*Error (not in Base)*/}}

Example: Person, Student A person has a name, an age and can speak A student is a person with a gpa Person name: String age: int speak: void Student gpa: double derived from

Person class public class Person{ public String name; // any name is OK private int age; // 0<=age<=130 public Person(){ //Call the other constructor this("someone",20);} public Person(String s, int a){ name = s; setAge(a); } public void setAge(int a){ if (a>=0 && a<=130) age=a;} public int getAge(){return age;} public void speak(){ System.out.println("Hi, I am "+name);} }

Student class public class Student extends Person{ private double gpa; public Student(){ // Person() called automatically gpa = 3.5;} public Student(String s,int a,double g) { //Call the constructor Person (s,a) super(s,a); //Don't write Person(s,a) setGPA(g); } public void setGPA(double g){ if (g>=0 && g<=4.0) gpa=g;} public double getGPA(){return gpa;}

Using Person and Student Person p = new Person("Jane",25); Student s = new Student("Robert",28,3.8); p.speak(); // a person can speak s.speak(); // a student can speak, since // a student is a person

Static and dynamic types // Can also write Person r = new Student("Sandra",28,3.9); The type used to declared r is Person = static type of r r points to a Student object. Student is the dynamic type of r. The static type of a variable never changes. The dynamic type may change r = new Person(“Sandra, 28); // Dynamic type = Person Or may not be defined r = null;

Method overriding How can we specialize speak for the Student class? Redefine speak within the Student class public void speak(){ super.speak();//let the Person speak // Add what the student say System.out.println("My gpa is "+gpa); } For any Student instance s, s.speak() invokes the speak method of the Student class. This is called method overriding.

this keyword revisited this: two uses a reference to the current object when within one of the object instance methods Use this(argument list) when calling another constructor from a constructor (within the same class). The call must be the first executed statement in the constructor. public Person(){ System.out.println ("Default constructor"); this(name,20); /*Error*/}

super keyword super: two uses a reference to the base object part of the current derived object within one of the derived object instance method. super.speak();//In Student.speak() Use super(argument list) when calling a base constructor from a derived constructor. The call must be the first executed statement in the constructor. super(s,a);//In Student constructor Can't chain the super calls super.super.method();//Error

Constructor calls When calling a constructor, Java invokes the base class constructor (if necessary via an implicit call to super()). initializes the instance variables of the current class executes the statements in the constructor of the current class. public class Derived extends Base{ private int i=3; public Derived(){i++;}} Derived d = new Derived(); // call Base(), set i to 3, increment i // What happens if Base is derived from // some other class?

Overloading and Overriding Method overloading: same name but a different number or type of arguments. A subclass can define some overloaded methods that augment the inherited overloaded methods provided by a superclass. Method overriding: define a method in the subclass with the same signature (return type and arguments) as the inherited method. The method in the subclass shadows the method of the superclass. Powerful when dealing with a hierarchy of objects (polymorphism: next slide)

Polymorphism example Consider Person[] group=new Person[2]; group[0]=new Person("Jane",25); group[1]=new Student("Bob",26,3.9); //OK, a Student is a Person for(int i=0; i<2; i++) group[i].speak(); // What is printed?

Polymorphism If there are several implementations of a method in the inheritance hierarchy of an object, the one in the most derived class always overrides the others. This is the case even if we refer to the object by way of a less derived type. group[1].speak(); //invokes speak of Student = dynamic // type of group[1]

Dynamic binding and Polymorphism Polymorphism uses dynamic binding The selection of the method is done at run time. The JVM starts looking in the dynamic type of the variable In Java, instance methods are by default dynamic (not the case in C++). To prevent overriding, declare the method final. public final void speak() { /* speak code in Person */} Can’t write in Student class public void speak(){/* code */} // Compilation error

Static binding and Overloading Overloading uses static binding The selection of the method is done at compile time. If in the Student class, we write instead public void speak(String s){ //overload speak of Person //takes a String as a formal parameter super.speak(); System.out.println(s);} Then Person p = new Student(); p.speak(); //invokes Person.speak()

Static methods (1) Reminder: static methods are not attached to any instance of a class. They belong to the class. A static method is invoked by using the class name. They are bound at compile time (That's why they are called static) Math.sqrt(2); A static method can't be overridden. You can't declare in a subclass as a non static method a superclass static method. However, you can shadow a superclass static method in the subclass (unless the superclass method was declared final).

Static methods (2) public class Base{ public static void foo(){ System.out.println("foo of Base");} } public class Derived extends Base{ public void foo(){/*Code*/} // Error public static void foo(){ // OK System.out.println("foo of Derived");}

final keyword final When applied to a method, the method can't be overidden (or shadowed for a static method) When applied to a class, the class can't be inherited. public final class ThisIsIt{ // class code } public class MoreOfIt extends ThisIsIt {} // Error None of the methods in a final class are overridden. The compiler can optimize the use of the class methods (inlining).