COSC This week. Will Learn
|
|
- Monica Weaver
- 5 years ago
- Views:
Transcription
1 This week COSC Read chapters 9, 11 S tart thinking about assignment 2 Week 4. J anuary 26, 2004 Will Learn how to inherit and override superclass methods how to invoke superclass constructors about protected and package access control Will Learn About abstract classes about interfaces to convert between supertype and subtype references the concept of polymorphism how interfaces can be used to decouple classes common superclass Object and to override its tos tring, equals, and clone methods Inheritanc e: c onomy and Humility (Meyer) Don t redo what has already been done. We could reach so high only because we stand on the shoulders of giants (Newton) Without inheritance every new class has to define all services it offers. S upports Open-Closed Principle: Open: still available for extension Closed: available for use by clients public class A //superclas private int x; public A() x = 1; public int getx() return x; public void setx(int x) this.x = x; xtending classes public class B extends A // subclass private int y; public B() y = 1; public int gety() return y; public void sety(int y) this.y = y; 1
2 xtending classes Get all of the public/protected fields/methods S o getx, setx, gety, sety for B What happens when an instance of B is created? Note that B has two attributes x and y. xtending classes: constructors Construction of subclass involves construction of superclass Java will call a Constructor - by default A() public class B extends A private int y; public B() y = 1; public int gety() return y; public void sety(int y) this.y = y; xtending classes: constructors If the first statement of the constructor is not super( ) or this( ), J ava inserts a super() If a class has no constructor, java creates a default one public ThisClass() super(); xtending classes: casting You can cast from one class to another Always possible going up the hierarchy Can cast anything to Object Can only cast down if the object is an instance of the class or one of its subclasses A a = new A(); B b = new B(); A temp = (A)b; Object temp = (Object) a; B test = (B) a; // will fail xtending classes: casting instanceof operator objectinstance instance of Class is a boolean Returns true iff the cast would succeed. xtending classes: fields J ava supports early binding for fields Which field is to be used is defined at compile time Inherit field: All fields from the superclass are automatically inherited Add field: S upply a new field that doesn't exist in the superclass Can't override fields 2
3 xtending classes: class methods J ava supports early binding for class methods (static methods) Which class method to be used is defined at compile time. Inheritanc e and Methods Override method: S upply a different implementation of a method that exists in the superclass Inherit method: Don't supply a new implementation of a method that exists in the superclass Add method: S upply a new method that doesn't exist in the superclass xtending classes: methods J ava supports late binding for instance methods Which method to be used is defined at run time // from java in a nutshell class A // Define a class named A int i = 1; // An instance field int f() return i; // An instance method static char g() return 'A'; // A class method class B extends A // Define a subclass of A int i = 2; // Shadows field i in class A int f() return -i; // Overrides instance method f in class A static char g() return 'B'; // Shadows class method g() in class A public class OverrideTest public static void main(string args[]) B b = new B(); // Creates a new object of type B System.out.println(b.i); // Refers to B.i; prints 2 System.out.println(b.f()); // Refers to B.f(); prints -2 System.out.println(b.g()); // Refers to B.g(); prints B System.out.println(B.g()); // This is a better way to invoke B.g() A a = (A) b; // Casts b to an instance of class A System.out.println(a.i); // Now refers to A.i; prints 1 System.out.println(a.f()); // Still refers to B.f(); prints -2 System.out.println(a.g()); // Refers to A.g(); prints A System.out.println(A.g()); // This is a better way to invoke A.g() BankAc c ount xample SavingsAccount New method addinterest transfer deposit addinterest deposit balance withdraw transfer Balance interestrate getbalance getbalance withdraw 3
4 Bank Account xample SavingAccount objects behave like BankAccount objects in many ways Savings account = bank account with interest All methods of are automatically inherited May call on object An Inheritanc e Diagram BankAc c ount xample public class BankAccount public BankAccount() //constructor public BankAccount(double initialbalance) //constructor public void deposit(double amount) //update balance public void withdraw(double amount) //update balance public double getbalance() //accessor public void transfer(bankaccount other, double amount) private double balance; //data Class BankAccount public class BankAccount public BankAccount() balance = 0; public BankAccount(double initialbalance) balance = initialbalance; public void deposit(double amount) balance = balance + amount; public void withdraw(double amount) balance = balance - amount; public double getbalance() return balance; public void transfer(bankaccount other, double amount) withdraw(amount); other.deposit(amount); private double balance; Adding a Subclass Method Layout of a Subclass Object!" $ " %!&'((! 4
5 CheckingAccount deductfees is a new method; deposit and withdraw are redefined (overriden) deductfees deposit transfer balance transactioncount withdraw getbalance CheckingAccount Class First three transactions are free Charge $2 for every additional transaction Must override to increment transaction count ) method deducts accumulated fees, resets transaction count Bank Account Hierarchy /** CheckingAccount A checking account that charges transaction fees. */ public class CheckingAccount extends BankAccount public CheckingAccount(int initialbalance) //body delted public void deposit(double amount) //body deleted public void withdraw(double amount) //body deleted public void deductfees() //body deleted private int transactioncount; private static final int FR_TRANSACTIONS = 3; private static final double TRANSACTION_F = 2.0; Inherited Fields are Private Consider method of * * ++ &&,,, Inherited Fields are Private Consider method of * * ++, ", + Can't just add to is a private field of the superclass Will not WORK 5
6 Inherited Fields are Private Consider method of * * ++ Can't just call in method of * That is the same as, Calls the same method (infinite recursion) Invoking a Superclass Method Instead, invoke superclass me thod, Now calls method of class Complete method: * ++, CheckingAccount /** A checking account that charges transaction fees. */ public class CheckingAccount extends BankAccount public CheckingAccount(int initialbalance) //construct superclass super(initialbalance); //initialize transaction count transactioncount = 0; public void deposit(double amount) transactioncount++; //now add amount to balance super.deposit(amount); public void withdraw(double amount) transactioncount++; //now subtract amount from balance super.withdraw(amount); /** Deducts the accumulated fees and resets the transaction count. */ public void deductfees() if (transactioncount > FR_TRANSACTIONS ) double fees = TRANS ACTION_F * (transactioncount - FR_TRANS ACTIONS ); super.withdraw(fees); transactioncount = 0; private int transactioncount; private static final int FR_TRANSACTIONS = 3; private static final double TRANSACTION_F = 2.0; Converting from Subclasses to Superclasses Ok to convert subclass reference to superclass reference ) " '( ") -. -.") S uperclass references don't know:,$ &&/!!-! Why would anyone want to know le ss about an object? 6
7 Polymorphis m Generic method: Works with any kind of bank account (plain, checking, savings) 0, S ubclass object reference converted to superclass reference, '(((1* 2 Access Control Level (accessible by subclasses and package) package access (the default, no modifier) Recommended Access Levels Fields: Always constants Methods: or Classes: or package Beware of accidental package access (forgetting or ) Inheritanc e Hierarc hies Hierarchies of classes, subclasses, and sub-subclasses are common xample: S wing hierarchy S uperclass 4* has methods 56 class has methods to set/get button text and icon A Part of the Hierarchy of Swing UI Components Object: The Cosmic Superclass All classes extend -. Most useful methods:
8 The Object Class is the Superclass of very J ava Class Overriding the Method Returns a string representation of the object Useful for debugging xample:!, returns something like.,,! 8"91"'(":(";(< tostring used by concatenation operator means , prints class name and object address =:>?( Override 8 "@+ +@<@,,, Overriding the equals Method 3 7 tests for equal contents == tests for equal location Must cast the -.parameter to subclass 3 * * "* -.,7, AA "", Two References to qual Objec ts Two References to Same Objec t Overriding the Method Copying object reference gives two references to same object :" '; S ometimes, need to make a copy of the object Use clone: :" ', (); Must cast return value because return type is -. Define method to make new object: -. ", " 8
9 Abstract Class A class not fully specified contains abstract methods: empty body may contain concrete definitions of methods may contain instance variables Cannot be instantiated Can be extended A subclass may be abstract or concrete A concrete subclass must provide implementation for all abstract methods xample: java.lang.number Number class in java.lang package is an abstract class Integer and Double in java.lang extend Number Methods intvalue and doublevalue are abstract methods in Number, but implemented in concrete subclasses Abstract classes public abstract class Box public final int CAPACITY = 100; private int count; public BOX() count = 0; public int getcount() return count; public boolean ismpty() return count == 0; public boolean isfull () return count == CAPACITY; public abstract boolean put(object o); public abstract boolean remove(object o); public abstract boolean has(object o); Abstract classes Forces implementor of an extension to Box to define abstract methods public abstract boolean put(object o); public abstract boolean remove(object o); public abstract boolean has(object o); Implementor may choose Arrays for implementation or other data types public class ArrayBox extends Box public class ArrayBox extends Box public ArrayBox() items = new Objects[CAPACITY]; public boolean put(object o) if (isfull()) return false; else items[count++] = o; return true; private Object[] items; Abstract Classes Great for specifying what needs to be done rather than how it should be done They capture design decisions They facilitate code re use by capturing commonality They defer implementation to later phases 9
10 Interfac e: Motivation S uppose we would like to develop a class called DataS et for a collection of bank accounts or coins keeping track of: the bank account/coin with maximim balance/value in the collection the total sum of account-balances/coin values the count of bank accounts/coins seen Firs t Solution Develop a DataS et for bank accounts Develop a DataS et for coins B for Bank Accounts B B,,, "+, ""(CC, D, " ++ B for Coins B B,,, * "+,F F ""( CC,F F D,F F " ++ * * This solution is bad the code for bank account and coin are the same except each uses a different object repetition leads to code bloat and hence code complexity if they share an inte rface, then DataS et need not know which object it is using If it was not for a common interface, then you would need a new license each time you bought a different car :-) Interfac e S uppose various classes could agree on the same method name, Then B could call that method: "+, ""( CC, D, " Define an interface: 10
11 Generic B B for Meas urable Objec ts B,,, "+, ""( CC, D, " ++ Realizing an Interfac e Class names interface(s) in clause Class supplies definitions of interface methods class ClassName implements Measurable public double getmeasure() imple me ntation a dditional me thods and fie lds The class must define the methods as Making and * Classes Measurable * File DataSetTes t.java 1 /** 2 This program tests the DataSet class. 3 */ 4 public class DataSetTest 5 6 public static void main(string[] args) DataSet bankdata = new DataSet(); bankdata.add(new BankAccount(0)); 12 bankdata.add(new BankAccount(10000)); 13 bankdata.add(new BankAccount(2000)); S ystem.out.println("average balance = " 16 + bankdata.getaverage()); 17 Measurable max = bankdata.getmaximum(); 18 System.out.println("Highest balance = " 19 + max.getmeasure()); DataSet coindata = new DataSet(); coindata.add(new Coin(0.25, "quarter")); 24 coindata.add(new Coin(0.1, "dime")); 25 coindata.add(new Coin(0.05, "nickel")); S ystem.out.println("average coin value = " 28 + coindata.getaverage()); 29 max = coindata.getmaximum(); 30 S ystem.out.println("highest coin value = " 31 + max.getmeasure()); UML Diagram of DataSet and Related Classes Note that B is de couple d from * 11
12 Interfac e Objects need to know how to interact with one another Interfaces specify what messages are acceptable to be sent to an object A message is sent to an object by a method call Interfaces enforce API Interfac e Can think of it as an abstract class that defines no methods and has no instance varaibles public interface Account public void deposit(float amount); public float balance(); public void withdraw(float amount); Interfac e Can define constants (static final) Classes do not extend interfaces, but implement them public class SavingsAccount implements Account public void deposit(float amount).. Interfac e Can extend a class and implement an interface public class SeniorSavingsAccount extends SavingsAccount implements Account public void deposit(float amount).. Interfac e Interfaces can extend other interfaces public interface VisaAccount extends Account public float fee(); Classes can implement multiple interfaces public class SeniorSavingsAccount extends SavingsAccount implements Account, SomeOtherInterface public void deposit(float amount).. Interfac e A class that implements an interface, must implement all its methods This ensures the class have methods with the given signatures Interfaces like abstract classes are useful for specifying what is expected rather than how it should be carried out. 12
13 Converting Between Types Can convert from class type to realized interface type: " '(((( " &&-G S ame interface type variable can hold reference to Coin " * (,'@@ &&-G Cannot convert between unrelated types "! 9'(:(;( &&/!!-! Casts Add coin objects to B B B" B B, * (,:9@7@ B, * (,'@@,,, Get largest coin with method: " B, What can you do with it? It's not of type * ",H &&/!!-! You know it's a coin, but the compiler doesn't. Apply a cast: * * "* "*,H If you are wrong and is n't a coin, the compiler throws an exception Interfaces vs. Classes All methods in an interface are abstract--no implementation All methods in an interface are automatically public An interface doesn't have instance fields This week Read chapters 9 & 11 S tart thinking about assignment 2 13
CHAPTER 10 INHERITANCE
CHAPTER 10 INHERITANCE Inheritance Inheritance: extend classes by adding or redefining methods, and adding instance fields Example: Savings account = bank account with interest class SavingsAccount extends
More informationInheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13
Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13 Fall 2006 Adapted from Java Concepts Companion Slides 1 Chapter Goals To learn about inheritance To understand how
More informationInheritance (P1 2006/2007)
Inheritance (P1 2006/2007) Fernando Brito e Abreu (fba@di.fct.unl.pt) Universidade Nova de Lisboa (http://www.unl.pt) QUASAR Research Group (http://ctp.di.fct.unl.pt/quasar) Chapter Goals To learn about
More informationChapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy
Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package access control To
More informationIntro to Computer Science 2. Inheritance
Intro to Computer Science 2 Inheritance Admin Questions? Quizzes Midterm Exam Announcement Inheritance Inheritance Specializing a class Inheritance Just as In science we have inheritance and specialization
More informationCHAPTER 9 INTERFACES AND POLYMORPHISM
CHAPTER 9 INTERFACES AND POLYMORPHISM Using Interfaces for Code Reuse Use interface types to make code more reusable In Chapter 6, we created a DataSet to find the average and maximum of a set of values
More informationChapter 10 Inheritance. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.
Chapter 10 Inheritance Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package
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 informationChapter 9. Interfaces and Polymorphism. Chapter Goals. Chapter Goals. Using Interfaces for Code Reuse. Using Interfaces for Code Reuse
Chapter 9 Interfaces and Polymorphism Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand the concept of polymorphism To appreciate how interfaces
More informationInterfaces and Polymorphism Advanced Programming
Interfaces and Polymorphism Advanced Programming ICOM 4015 Lecture 10 Reading: Java Concepts Chapter 11 Fall 2006 Adapted from Java Concepts Companion Slides 1 Chapter Goals To learn about interfaces To
More informationHandout 9 OO Inheritance.
Handout 9 CS603 Object-Oriented Programming Fall 2016 Page 1 of 11 Handout 9 OO Inheritance. All classes in Java form a hierarchy. The top of the hierarchy is class Object Example: classicalarchives.com
More informationInheritance: Definition
Inheritance 1 Inheritance: Definition inheritance: a parent-child relationship between classes allows sharing of the behavior of the parent class into its child classes one of the major benefits of object-oriented
More informationInheritance & Abstract Classes Fall 2018 Margaret Reid-Miller
Inheritance & Abstract Classes 15-121 Margaret Reid-Miller Today Today: Finish circular queues Exercise: Reverse queue values Inheritance Abstract Classes Clone 15-121 (Reid-Miller) 2 Object Oriented Programming
More informationCS1083 Week 3: Polymorphism
CS1083 Week 3: Polymorphism David Bremner 2018-01-18 Polymorphic Methods Late Binding Container Polymorphism More kinds of accounts DecimalAccount BigDecimal -balance: BigDecimal +DecimalAccount() +DecimalAccount(initialDollars
More information3/7/2012. Chapter Ten: Inheritance. Chapter Goals
Chapter Ten: Inheritance Chapter Goals To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
More informationC# Programming for Developers Course Labs Contents
C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring
More informationPrinciples of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad
Principles of Software Construction: Objects, Design and Concurrency 15-214 toad Inheritance, type-checking, and method dispatch Fall 2013 Jonathan Aldrich Charlie Garrod School of Computer Science 2012-13
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 informationPrinciples of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012
Principles of Software Construction: Objects, Design and Concurrency Polymorphism, part 2 15-214 toad Fall 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 C Garrod, J Aldrich, and
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes
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 informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes
More informationInheritance and Subclasses
Software and Programming I Inheritance and Subclasses Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Packages Inheritance Polymorphism Sections 9.1 9.4 slides are available at www.dcs.bbk.ac.uk/
More informationindex.pdf January 21,
index.pdf January 21, 2013 1 ITI 1121. Introduction to Computing II Circle Let s complete the implementation of the class Circle. Marcel Turcotte School of Electrical Engineering and Computer Science Version
More informationLesson 35..Inheritance
Lesson 35..Inheritance 35-1 Within a new project we will create three classes BankAccount, SavingsAccount, and Tester. First, the BankAccount class: public class BankAccount public BankAccount(double amt)
More informationPrinciples of Software Construction: Objects, Design, and Concurrency
Principles of Software Construction: Objects, Design, and Concurrency An Introduction to Object-oriented Programming, Continued. Modules and Inheritance Spring 2014 Charlie Garrod Christian Kästner School
More informationPractice 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 informationInheritance. Inheritance
1 2 1 is a mechanism for enhancing existing classes. It allows to extend the description of an existing class by adding new attributes and new methods. For example: class ColoredRectangle extends Rectangle
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 informationSoftware and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London
Software and Programming I Classes and Arrays Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Class Object Interfaces Arrays Sections 9.5 9.6 Common Array Algorithms Sections 6.1
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 informationCheck out Polymorphism from SVN. Object & Polymorphism
Check out Polymorphism from SVN Object & Polymorphism Inheritance, Associations, and Dependencies Generalization (superclass) Specialization (subclass) Dependency lines are dashed Field association lines
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 informationContainer Vs. Definition Classes. Container Class
Overview Abstraction Defining new classes Instance variables Constructors Defining methods and passing parameters Method/constructor overloading Encapsulation Visibility modifiers Static members 14 November
More informationCSC 222: Object-Oriented Programming. Fall Inheritance & polymorphism
CSC 222: Object-Oriented Programming Fall 2015 Inheritance & polymorphism Hunt the Wumpus, enumerated types inheritance, derived classes inheriting fields & methods, overriding fields and methods IS-A
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 informationCSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN
CSSE 220 Day 15 Inheritance Check out DiscountSubclasses from SVN Discount Subclasses Work in pairs First look at my solution and understand how it works Then draw a UML diagram of it DiscountSubclasses
More informationCN208 Introduction to Computer Programming
CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every
More informationContents. 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 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 informationThe Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3
COSC 123 Computer Creativity Course Review Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Reading Data from the User The Scanner Class The Scanner class reads data entered
More informationMore Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.
More Java Basics 1. INHERITANCE AND DYNAMIC TYPE-CASTING Java performs automatic type conversion from a sub-type to a super-type. That is, if a method requires a parameter of type A, we can call the method
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 informationAn introduction to Java II
An introduction to Java II Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 4-1 Java: Generalities A little
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 informationCS250 Intro to CS II. Spring CS250 - Intro to CS II 1
CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining
More informationpublic class Account { private int id; private static int nextaccountid = 0; private String name; private double balance;
public class Account { private int id; private static int nextaccountid = 0; private String name; private double balance; public double deposit(double amount) { public double withdraw(double amount) {
More informationBinghamton University. CS-140 Fall Chapter 9. Inheritance
Chapter 9 Inheritance 1 Shapes Created class Point for (x,y) points Created classes: Rectangle, Circle, RightTriangle All have llc field All have dimensions, but different for each shape All have identical
More informationCSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes
CSEN401 Computer Programming Lab Topics: Introduction and Motivation Recap: Objects and Classes Prof. Dr. Slim Abdennadher 16.2.2014 c S. Abdennadher 1 Course Structure Lectures Presentation of topics
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 informationObject-Oriented Programming
Abstract classes Object-Oriented Programming Outline Abstract classes Abstract methods Design pattern: Template method Dynamic & static binding Upcasting & Downcasting Readings: HFJ: Ch. 8. GT: Ch. 8.
More informationSTUDENT LESSON A5 Designing and Using Classes
STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of
More informationQuarter 1 Practice Exam
University of Chicago Laboratory Schools Advanced Placement Computer Science Quarter 1 Practice Exam Baker Franke 2005 APCS - 12/10/08 :: 1 of 8 1.) (10 percent) Write a segment of code that will produce
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 informationAdministrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments
CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised
More informationUse the scantron sheet to enter the answer to questions (pages 1-6)
Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object
More informationPrinciples of Software Construction: Objects, Design, and Concurrency. Part 1: Designing Classes. Design for Reuse School of Computer Science
Principles of Software Construction: Objects, Design, and Concurrency Part 1: Designing Classes Design for Reuse Charlie Garrod Michael Hilton School of Computer Science 1 Administrivia HW2 due Thursday
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 informationEncapsulation. Mason Vail Boise State University Computer Science
Encapsulation Mason Vail Boise State University Computer Science Pillars of Object-Oriented Programming Encapsulation Inheritance Polymorphism Abstraction (sometimes) Object Identity Data (variables) make
More informationCSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism
CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism Review from Lecture 22 Added parent pointers to the TreeNode to implement increment and decrement operations on tree
More informationObject-Oriented Programming (Java)
Object-Oriented Programming (Java) Topics Covered Today 2.1 Implementing Classes 2.1.1 Defining Classes 2.1.2 Inheritance 2.1.3 Method equals and Method tostring 2 Define Classes class classname extends
More informationCH. 2 OBJECT-ORIENTED PROGRAMMING
CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED
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 informationInheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass
Inheritance and Polymorphism Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism Inheritance (semantics) We now have two classes that do essentially the same thing The fields are exactly
More informationInheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L
Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive
More informationCS 170, Section /3/2009 CS170, Section 000, Fall
Lecture 18: Objects CS 170, Section 000 3 November 2009 11/3/2009 CS170, Section 000, Fall 2009 1 Lecture Plan Homework 5 : questions, comments? Managing g g Data: objects to make your life easier ArrayList:
More informationAdvanced 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 informationVIRTUAL FUNCTIONS Chapter 10
1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions
More informationSoftware Paradigms (Lesson 3) Object-Oriented Paradigm (2)
Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3
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 informationIslamic University of Gaza Faculty of Engineering Computer Engineering Department
Student Mark Islamic University of Gaza Faculty of Engineering Computer Engineering Department Question # 1 / 18 Question # / 1 Total ( 0 ) Student Information ID Name Answer keys Sector A B C D E A B
More informationSuper-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 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 informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:
More informationOOP: Key Concepts 09/28/2001 1
OOP: Key Concepts Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring 09/28/2001 1 Overview of Part
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationCSC Inheritance. Fall 2009
CSC 111 - Inheritance Fall 2009 Object Oriented Programming: Inheritance Within object oriented programming, Inheritance is defined as: a mechanism for extending classes by adding variables and methods
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 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 informationPrinciples of Software Construction: Objects, Design and Concurrency. Packages and Polymorphism. toad Fall 2012
Principles of Software Construction: Objects, Design and Concurrency Packages and Polymorphism 15-214 toad Fall 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 C Garrod, J Aldrich,
More informationRecords. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05
Records CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 15: Objects 25 Feb 05 Objects combine features of records and abstract data types Records = aggregate data structures Combine several
More information2. The object-oriented paradigm!
2. The object-oriented paradigm! Plan for this section:! n Look at things we have to be able to do with a programming language! n Look at Java and how it is done there" Note: I will make a lot of use of
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 26 March 26, 2015 Inheritance and Dynamic Dispatch Chapter 24 public interface Displaceable { public int getx(); public int gety(); public void move
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationWhere do we stand on inheritance?
In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public
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 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 informationObject-oriented basics. Object Class vs object Inheritance Overloading Interface
Object-oriented basics Object Class vs object Inheritance Overloading Interface 1 The object concept Object Encapsulation abstraction Entity with state and behaviour state -> variables behaviour -> methods
More informationOutline. 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 informationChapter Nine: Interfaces and Polymorphism. Big Java by Cay Horstmann Copyright 2008 by John Wiley & Sons. All rights reserved.
Chapter Nine: Interfaces and Polymorphism Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand the concept of polymorphism To appreciate how
More information3/7/2012. Chapter Nine: Interfaces and Polymorphism. Chapter Goals
Chapter Nine: Interfaces and Polymorphism Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand the concept of polymorphism To appreciate how
More information10/27/2011. Chapter Goals
Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand the concept of polymorphism To appreciate how interfaces can be used to decouple classes
More informationAgenda: Notes on Chapter 3. Create a class with constructors and methods.
Bell Work 9/19/16: How would you call the default constructor for a class called BankAccount? Agenda: Notes on Chapter 3. Create a class with constructors and methods. Objectives: To become familiar with
More informationOverview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008
Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object
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 informationCS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08
CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly
More informationObjects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017
Objects and Classes Lecture 10 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 All labs have been published Descriptions
More information