COE318 Lecture Notes Week 8 (Oct 24, 2011)

Size: px
Start display at page:

Download "COE318 Lecture Notes Week 8 (Oct 24, 2011)"

Transcription

1 COE318 Software Systems Lecture Notes: Week 8 1 of 17 COE318 Lecture Notes Week 8 (Oct 24, 2011) Topics == vs..equals(...): A first look Casting Inheritance, interfaces, etc Introduction to Juni (unit testing) Vocabulary There are new words and concepts to learn this week including: inheritance (subclassing) subclass superclass extends implements Exception try catch casting abstract interface overrides overloads super(...) this(...) super.foo(...) instanceof marker interface

2 COE318 Software Systems Lecture Notes: Week 8 2 of 17 polymorphism == vs. equals(...) For primitive data types (int, double, boolean, char, etc.) the only way to test if two values are equal is with ==; thus if i and j are ints then (i == j) is true if and only if they both have the same value. For reference data types, however, you can test for different types of equality : It is legal (but usually wrong) to use == just as with primitive types. Two reference objects are equal in this sense only if they refer to the identical object. The equals(...) method is almost always the correct way to check for equality of two reference variables. Consider the example below (where we assume a ComplexNukber class similar to what you did in the lab except that it has an equals() method that returns true if both complex numbers have exactly the same real and imaginary parts.) ComplexNumber w, y, z; w = new ComplexNumber(1, 2); z = new ComplexNumber(1, 2); y = z; //Now w == z is false; they are different objects! //But w.equals(z) is true since they represent the same //complex number. //Both y == z and y.equals(z) are true since they are //the same object. Casts primitive data types come in different sizses; an int is a 32-bit signed integer; a short is 16-bits; a byte is 8 bits and a long is 64 bits; When a smaller type is assigned to a larger type, a cast is required. This kind of primitive data casting is the same as in C. In the following example, all the casts are necessary (or there will be compilation errors.) We will consider casting of reference type data later on. public class Casts { public static void main(string[] args) { byte b = 1; short s = 1;

3 COE318 Software Systems Lecture Notes: Week 8 3 of 17 int i = 0x7fff0005; s = (short) i; System.out.println("s: " + s); System.out.println("i: " + i); double d = 2.99; i = (int) d; System.out.println("i: " + i); s = -1; char ch = (char) s; i = s; System.out.println("i: " + i); i = ch; System.out.println("i: " + i); By the way, the output from this program is: s: 5 i: i: 2 i: -1 i: Can you see why this is the output? (Hint: when something is too big for a smaller number of bytes, it is truncated. Also, all numbers in Java are signed except for char which is 16-bit unsigned (short is 16-bit signed.)) Will be explained in next lecure. Zoo: Version 1 This simple version models a Zoo that contains an arbitrary number of Lions. There is nothing new here. It's just a starting point for exploring, using and understanding some important features of object-oriented programming. But, some notes... The instance variables of Lion are private and final. Consequently, Lion objects are (for the moment) immutable. public class Lion {

4 COE318 Software Systems Lecture Notes: Week 8 4 of 17 private final String name; private final int birthyear; public Lion(String name, int year) { this.name = name; birthyear = year; public int age() { return birthyear; public String getname() { return name; public String noise() { return "GGGrowl"; public boolean eatspeople() { return true; import java.util.arraylist; public class Zoo { private final ArrayList<Lion> lions = new ArrayList<Lion>(); public void add(lion lion) { lions.add(lion); public String getnames() { String s = ""; for(lion leo : lions) { s += leo.getname() + "\n";

5 COE318 Software Systems Lecture Notes: Week 8 5 of 17 return s; public static void main(string[] args) { Zoo zoo = new Zoo(); Lion a = new Lion("Alex", 2010); zoo.add(a); zoo.add(new Lion("Betty", 2009)); System.out.println(zoo.getNames()); Zoo Version 2: A First Look at Inheritance The zoo wants to have more animals than just lions. But proceeding as before would be very tedious if, say, there were 100 different kinds of animals: We'd need to create Pig, Cat, Crocodile, Elephant, Hummingbird, etc. classes and they would all have just about the same code; We'd need separate ArrayLists for each type of animal in the Zoo class. It would be difficult to treat all the animals as a group: to sort them alphabetically by name or by age, for example. Inheritance (subclassing) to the rescue! We can put practically all the code for Lion into another class we call AbstractAnimal. (Why not call it Animal instead of AbstractAnimal? Good question! To be explained in the next version.) We can then rewrite the Lion class to extend the AbstractAnimal class; all of its methods are inherited by Lion and do not have to be copied and pasted. The Lion class now looks like: public class Lion extends AbstractAnimal { public Lion(String name, int year) { super(name, year);

6 COE318 Software Systems Lecture Notes: Week 8 6 of 17 But what's this super(name, year); stuff? It invokes the constructor (with the same signature) of its superclass. It is not always necessary to invoke the superclass constructor as is done here; however, If your do, it must be the first statement in the subclass's constructor. The superclass is AbstractAnimal and here's what it looks like: public class AbstractAnimal { private final String name; private final int birthyear; public AbstractAnimal(String name, int year) { this.name = name; birthyear = year; public int age() { return birthyear; public String getname() { return name; public String noise() { return "GGGrowl"; public boolean eatspeople() { return true; We can now write the Hedgehog class. However, the inherited methods eatspeople() and noise() give the wrong answer for a hedgehog. An inherited method can be overridden by simply re-writing it. (A subclass almost always overrides at least one method from its superclass.)

7 COE318 Software Systems Lecture Notes: Week 8 7 of 17 Note: The line is not required. It can be useful for the compiler and some tools. Netbeans recommends you put it in. It also reminds programmers that they are modifying an inherited method.) In general, lines beginning are called annotations. Programmers can define their own annotations but that is beyond the scope of this course.) public class Hedgehog extends AbstractAnimal { public Hedgehog(String name, int year) { super(name, year); public boolean eatspeople() { return false; How do we declare the data type of a Lion or Hedgehog? In the past (before inheritance), this question would appear foolish. For example, we would write things like: Resistor r; r = new Resistor(10); r.setvoltage(10); There would be no other choice. But with inheritance we can declare a Lion as either of type Lion or type AbstractAnimal: Lion p = new Lion( Leo ); AbstractAnimal q = new Lion( Simba ); There is absolutely no difference between how p and q behave. They are both Lions and behave as such no matter how their data types were declared. And there is no difference in runtime efficiency. But declaring Lions or Hedgehogs or Pigs to be AbstractAnimals has big advantages. For example, the Zoo class can keep all of the animals in a single ArrayList<AbstractAnimal>. Below is the new, improved Zoo class: import java.util.arraylist;

8 COE318 Software Systems Lecture Notes: Week 8 8 of 17 public class Zoo { private final ArrayList<AbstractAnimal> animals = new ArrayList<AbstractAnimal>(); public void add(abstractanimal animal) { animals.add(animal); public String getnames() { String s = ""; for (AbstractAnimal a : animals) { s += a.getname() + "\n"; return s; public AbstractAnimal[] getanimals() { AbstractAnimal[] ts = new AbstractAnimal[0]; return animals.toarray(ts); public static void main(string[] args) { Zoo zoo = new Zoo(); Lion a = new Lion("Leo", 2010); zoo.add(a); zoo.add(new Lion("Simba", 2009)); zoo.add(new Hedgehog("Sonic", 2010)); System.out.println(zoo.getNames()); AbstractAnimal[] animals = zoo.getanimals(); for (AbstractAnimal an : animals) { System.out.println(an.getClass().getName() + " " + an.getname() + ": " + (an.eatspeople()? "eats" : "does not eat") + " people");

9 COE318 Software Systems Lecture Notes: Week 8 9 of 17 Zoo Version 3: Abstract classes and methods AbstractAnimal is just a normal class and it is legal to write: AbstractAnimal a = new AbstractAnimal( Sue ); This should not be allowed! It makes no sense to create an animal when we don't know what kind of animal it is. AbstractAnimal exists only for the purpose of subclassing. We can make this clear by declaring it to be abstract. The compiler will now disallow: AbstractAnimal a = new AbstractAnimal( Sue ); We now refer to AbstractAnimal as an abstract class that cannot be instantiated. But Lion and Hedgehog are concrete classes that can be instantiated. We can also declare methods to be abstract. If we do so, we must declare the class to be abstract. Furthermore, when we extend an abstract class as a concrete class, the compiler will insist that we write implementation code for any abstract methods. The code for our classes is given below. Note: the Zoo class needs no changes. The AbstractAnimal class is now declared abstract as is its noise() method. Both Lion and Hedgehog now have to implement (and not just inherit) the noise() method. public abstract class AbstractAnimal { private final String name; private final int birthyear; public AbstractAnimal(String name, int year) { this.name = name; birthyear = year; public int age() { return birthyear; public String getname() { return name;

10 COE318 Software Systems Lecture Notes: Week 8 10 of 17 public abstract String noise(); public boolean eatspeople() { return true; public class Hedgehog extends AbstractAnimal { public Hedgehog(String name, int year) { super(name, year); public boolean eatspeople() { return false; public String noise() { return "Chirp...chirp"; public class Lion extends AbstractAnimal { public Lion(String name, int year) { super(name, year); public String noise() { return "Rrroar (yum yum)";

11 COE318 Software Systems Lecture Notes: Week 8 11 of 17 Zoo Version 4: Interfaces The zoo owner is happy with version 3; lots and lots of concrete animal classes can be easily added; no changes needed to the Zoo or AbstractAnimal classes. But then one day he says, I love my fridge. I want to have it as one of the amimals in my zoo. The guy may be a lunatic, but we have to respect his wishes. Tell him just to subclass Refrigerator from AbstractAnimal. But he can't do that; Refrigerator is already subclassed from ElectricalAppliance. OK, we'll make an interface called Animal. He just has to implement the interface. What is an interface? An interface is simply a collection of zero or more public abstract methods. A class can implement as many interfaces as it wants. It just has to ensure that all the abstract methods are actually implemented. (And the compiler will ensure that this is done.) We also take advantage of the Animal interface and have AbstractAnimal implement it. Objects can be declared as their own type or as any of their superclass's type. In addition, an object can be declared as any interface type implemented by the actual class. Consequently, we can now declare all the animals (and the fridge) as type Animal. We also have AbstractAnimal implement a standard imterface, Comparable<Animal>. Note (lab 5): You are provided with an interface in lab 5: UserInterface which describes what the methods should do. The reason for this so that any user interface has the same mthods and can be easily plugged into the existing code. (A graphical user interface would have buttons and show the cards in a graphical way. A networked interface coudl also be written.) interface Animal { String noise(); boolean eatspeople(); int age(); String getname(); public abstract class AbstractAnimal implements Animal, Comparable<Animal> { private final String name; private final int birthyear;

12 COE318 Software Systems Lecture Notes: Week 8 12 of 17 public AbstractAnimal(String name, int year) { this.name = name; birthyear = year; public int age() { return birthyear; public String getname() { return name; public abstract String noise(); public boolean eatspeople() { return this instanceof Dangerous; public int compareto(animal other) { return getname().compareto(other.getname()); public boolean equals(object obj) { if (obj == null) { return false; if (getclass()!= obj.getclass()) { return false; final AbstractAnimal other = (AbstractAnimal) obj; if ((this.name == null)? (other.name!= null) :!this.name.equals(other.name)) { return false; return true;

13 COE318 Software Systems Lecture Notes: Week 8 13 of 17 public int hashcode() { int hash = 7; hash = 83 * hash + (this.name!= null? this.name.hashcode() : 0); return hash; public interface Dangerous { public class Lion extends AbstractAnimal implements Dangerous{ public Lion(String name, int year) { super(name, year); public String noise() { return "GGGrowl"; public class Hedgehog extends AbstractAnimal { public Hedgehog(String name, int year) { super(name, year);

14 COE318 Software Systems Lecture Notes: Week 8 14 of 17 public String noise() { return "Chirp chirp"; import java.util.arraylist; public class Zoo { private final ArrayList<Animal> animals = new ArrayList<Animal>(); public void add(animal animal) { animals.add(animal); public String getnames() { String s = ""; for (Animal a : animals) { s += a.getname() + "\n"; return s; public Animal[] getanimals() { Animal[] ts = new AbstractAnimal[0]; return animals.toarray(ts); public static void main(string[] args) { Zoo zoo = new Zoo(); Animal a = new Lion("Alex", 2010); zoo.add(a); zoo.add(new Lion("Betty", 2009)); zoo.add(new Hedgehog("Charlie", 2010)); System.out.println(zoo.getNames()); Animal[] animals = zoo.getanimals(); for (Animal an : animals) { System.out.println(an.getClass().getName() + " " + an.getname() + ": " + (an.eatspeople()? "eats" : "does not eat")

15 COE318 Software Systems Lecture Notes: Week 8 15 of 17 + " people"); Zoo Version 5: Exceptions import java.util.arraylist; public class Zoo { private final ArrayList<Animal> animals = new ArrayList<Animal>(); public void add(animal animal) { if (animals.contains(animal)) { throw new IllegalArgumentException("Duplicate name not allowed"); animals.add(animal); public String getnames() { String s = ""; for (Animal a : animals) { s += a.getname() + "\n"; return s; public Animal[] getanimals() { Animal[] ts = new AbstractAnimal[0]; return animals.toarray(ts); public static void main(string[] args) {

16 COE318 Software Systems Lecture Notes: Week 8 16 of 17 Zoo zoo = new Zoo(); Animal a = new Lion("Alex", 2010); zoo.add(a); zoo.add(new Lion("Betty", 2009)); Animal charlie1 = new Hedgehog("Charlie", 2010); zoo.add(charlie1); System.out.println(zoo.getNames()); Animal charlie2 = new Lion("Charlie", 2007); try { zoo.add(charlie2); catch (IllegalArgumentException ex) { System.err.println("Duplicate name not added"); Animal[] animals = zoo.getanimals(); for (Animal an : animals) { System.out.println(an.getClass().getName() + " " + an.getname() + ": " + (an.eatspeople()? "eats" : "does not eat") + " people"); Unit testing and Junit Unit testing (widely used in the software industry) allows you to write test methods independently for the implementation code. Netbeans supports a framefork for doing this with a prodcut called Junit. (We use version 4.) Test methods are annotated and must be public void. Suppose we have a class called Resistor (as in Lab 1). We could write a test method to verify that getvoltage() worked:

17 COE318 Software Systems Lecture Notes: Week 8 17 of 17 public void getvoltage() { Resistor r = new Resistor(10); r.setcurrent(30.); assertequals(300.0, r.getvoltage()); 1. Write an equals(object ob) for the ComplexNumber class. Answers 1. Just: public boolean equals(object ob) { if (ob == null) return false; if (!(ob instanceof ComplexNumber)) return false; ComplexNumber c = (ComplexNumber) ob; return (c.getreal() == getreal()) && (c.getimag() == getimag());

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012) COE318 Lecture Notes: Week 9 1 of 14 COE318 Lecture Notes Week 9 (Week of Oct 29, 2012) Topics The final keyword Inheritance and Polymorphism The final keyword Zoo: Version 1 This simple version models

More information

COE318 Lecture Notes Week 9 (Oct 31, 2011)

COE318 Lecture Notes Week 9 (Oct 31, 2011) COE318 Software Systems Lecture Notes: Week 9 1 of 12 COE318 Lecture Notes Week 9 (Oct 31, 2011) Topics Casting reference variables equals() and hashcode() overloading Collections and ArrayList utilities

More information

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

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 information

COE318 Lecture Notes Week 6 (Oct 10, 2011)

COE318 Lecture Notes Week 6 (Oct 10, 2011) COE318 Software Systems Lecture Notes: Week 6 1 of 8 COE318 Lecture Notes Week 6 (Oct 10, 2011) Topics Announcements final qualifiers Example: An alternative to arrays == vs..equals(...): A first look

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. 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 information

Java Magistère BFA

Java 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 information

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

Argument 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 information

Abstract Classes and Interfaces

Abstract 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

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

CMSC131. 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. 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 information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

The 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 information

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

Day 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 information

Object-Oriented Programming More Inheritance

Object-Oriented Programming More Inheritance Object-Oriented Programming More Inheritance Ewan Klein School of Informatics Inf1 :: 2009/10 Ewan Klein (School of Informatics) OOP: More Inheritance Inf1 :: 2009/10 1 / 45 1 Inheritance Flat Hierarchy

More information

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Announcement. 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 information

Java Fundamentals (II)

Java 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 information

What is Inheritance?

What 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 information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Object-Oriented Concepts

Object-Oriented Concepts JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing

More information

Rules and syntax for inheritance. The boring stuff

Rules 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 information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

INHERITANCE. Spring 2019

INHERITANCE. 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 information

CLASS DESIGN. Objectives MODULE 4

CLASS 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 information

Introduction to Inheritance

Introduction 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 information

1 Shyam sir JAVA Notes

1 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 information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

Object-Oriented ProgrammingInheritance & Polymorphism

Object-Oriented ProgrammingInheritance & Polymorphism Inheritance Polymorphism Overriding and Overloading Object-Oriented Programming Inheritance & Polymorphism Inf1 :: 2008/09 Inheritance Polymorphism Overriding and Overloading 1 Inheritance Flat Hierarchy

More information

Building Java Programs. Inheritance and Polymorphism

Building Java Programs. Inheritance and Polymorphism Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many

More information

CS-202 Introduction to Object Oriented Programming

CS-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 information

Basic Object-Oriented Concepts. 5-Oct-17

Basic Object-Oriented Concepts. 5-Oct-17 Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains

More information

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

Inheritance. 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 information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 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 information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA 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 information

AP CS Unit 6: Inheritance Notes

AP CS Unit 6: Inheritance Notes AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything

More information

Java Classes, Inheritance, and Interfaces

Java Classes, Inheritance, and Interfaces Java Classes, Inheritance, and Interfaces Introduction Classes are a foundational element in Java. Everything in Java is contained in a class. Classes are used to create Objects which contain the functionality

More information

Informatik II (D-ITET) Tutorial 6

Informatik II (D-ITET) Tutorial 6 Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,

More information

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. Inf1-OP Inheritance UML Class Diagrams UML: language for specifying and visualizing OOP software systems UML class diagram: specifies class name, instance variables, methods,... Volker Seeker, adapting

More information

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics Inf1-OP Inheritance Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 12, 2018 UML Class Diagrams UML: language for specifying and visualizing OOP software

More information

Logistics. Final Exam on Friday at 3pm in CHEM 102

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

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

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5, Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &

More information

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 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 information

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

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

type conversion polymorphism (intro only) Class class

type conversion polymorphism (intro only) Class class COMP 250 Lecture 33 type conversion polymorphism (intro only) Class class Nov. 24, 2017 1 Primitive Type Conversion double float long int short char byte boolean non-integers integers In COMP 273, you

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

COP 3330 Final Exam Review

COP 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 information

First IS-A Relationship: Inheritance

First 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 information

Inheritance and Polymorphism

Inheritance 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 information

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

CSCI-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 information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More 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 information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

Lecture 4: Extending Classes. Concept

Lecture 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 information

Class, Variable, Constructor, Object, Method Questions

Class, 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 information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object 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 information

interface MyAnno interface str( ) val( )

interface MyAnno interface str( ) val( ) Unit 4 Annotations: basics of annotation-the Annotated element Interface. Using Default Values, Marker Annotations. Single-Member Annotations. The Built-In Annotations-Some Restrictions. 1 annotation Since

More information

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INTERFACES OOP using Java, from slides by Shayan Javed Interfaces 2 ANIMAL picture food sleep() roam() makenoise() eat() 3 ANIMAL picture food sleep() roam() makenoise() eat() 4 roam() FELINE

More information

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass Encapsulation Again Inheritance Encapsulation and Inheritance Inf1-OOP Inheritance and Interfaces Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics March 9, 2015 The Object

More information

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics Inf1-OOP Inheritance and Interfaces Ewan Klein, Perdita Stevens School of Informatics January 12, 2013 Encapsulation Again Inheritance Encapsulation and Inheritance The Object Superclass Flat vs. Nested

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

Informatik II Tutorial 6. Subho Shankar Basu

Informatik II Tutorial 6. Subho Shankar Basu Informatik II Tutorial 6 Subho Shankar Basu subho.basu@inf.ethz.ch 06.04.2017 Overview Debriefing Exercise 5 Briefing Exercise 6 2 U05 Some Hints Variables & Methods beginwithlowercase, areverydescriptiveand

More information

Java 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 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 information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR) Object Oriented Programming Part II of II Steve Ryder Session 8352 JSR Systems (JSR) sryder@jsrsys.com New Terms in this Section API Access Modifier Package Constructor 2 Polymorphism Three steps of object

More information

Chapter 11: Collections and Maps

Chapter 11: Collections and Maps Chapter 11: Collections and Maps Implementing the equals(), hashcode() and compareto() methods A Programmer's Guide to Java Certification (Second Edition) Khalid A. Mughal and Rolf W. Rasmussen Addison-Wesley,

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

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

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,

More information

Inheritance (continued) Inheritance

Inheritance (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 information

COE318 Lecture Notes Week 5 (Oct 3, 2011)

COE318 Lecture Notes Week 5 (Oct 3, 2011) COE318 Software Systems Lecture Notes: Week 5 1 of 6 COE318 Lecture Notes Week 5 (Oct 3, 2011) Topics Announcements Strings static and final qualifiers Stack and Heap details Announcements Quiz: Today!

More information

More Relationships Between Classes

More 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 information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013 1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

More information

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

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. 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 information

Chapter 14 Abstract Classes and Interfaces

Chapter 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 information

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes Java Curriculum for AP Computer Science, Student Lesson A20 1 STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes INTRODUCTION:

More information

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

CSE1720. 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 information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

CS/ENGRD 2110 SPRING 2018

CS/ENGRD 2110 SPRING 2018 1 The fattest knight at King Arthur's round table was Sir Cumference. He acquired his size from too much pi. CS/ENGRD 2110 SPRING 2018 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110

More information

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code: 1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code: public double getsalary() double basesalary = getsalary(); return basesalary + bonus; 3- What does the

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

Fundamental Java Methods

Fundamental Java Methods Object-oriented Programming Fundamental Java Methods Fundamental Java Methods These methods are frequently needed in Java classes. You can find a discussion of each one in Java textbooks, such as Big Java.

More information

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016 COMP 250 Lecture 32 polymorphism Nov. 25, 2016 1 Recall example from lecture 30 class String serialnumber Person owner void bark() {print woof } : my = new (); my.bark();?????? extends extends class void

More information

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals 1 CS/ENGRD 2110 FALL 2017 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110 Overview ref in JavaHyperText 2 Quick look at arrays array Casting among classes

More information

Java Object Oriented Design. CSC207 Fall 2014

Java 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 information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

Software Development (cs2500)

Software Development (cs2500) Software Development (cs2500) Lecture 31: Abstract Classes and Methods M.R.C. van Dongen January 12, 2011 Contents 1 Outline 1 2 Abstract Classes 1 3 Abstract Methods 3 4 The Object Class 4 4.1 Overriding

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This

More information

Chapter 9 Inheritance

Chapter 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 information

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals CS/ENGRD 2110 FALL 2018 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110 Overview references in 2 Quick look at arrays: array Casting among classes cast, object-casting

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

Java: introduction to object-oriented features

Java: 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 information