CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:
|
|
- Jack Dennis
- 5 years ago
- Views:
Transcription
1 CS-140 Fall 2018 Test 2 Version A Nov. 12, 2018 Name: 1. (10 points) For the following, Check T if the statement is true, or F if the statement is false. (a) X T F : A class in Java contains fields, and properties, and always explicitly or implicitly extends exactly one other class, and therefore inherits the fields and public instance methods from the extended class. Typo in this question... should have read A class in Java contains fields and methods... students who question properties get credit for a false response. (b) T X F : A referece variable may be declared with an interface as its type, but must refer to an instance of a real class that implements the interface. The reference variable can be used to invoke all of the methods in the real class. Only interface methods can be directly invoked from a reference variable with an interface type. The reference must be upcast to the actual class in order to reference methods defined in the real class that are not in the interface. (c) X T F : If a child overrides its parent s constructor it can still invoke the parent constructor with the super keyword, but if it does so, then it must invoke the parent constructor first. Technically, you cannot override your parent s constructor... but, by specifying nothing, you do inherit your parent s no-argument creator, so there is a sort of inheritance going on. (d) T X F : A child class can modify the private fields of the class that it extends. A child can only modify public or protected fields - not private fields. (e) X T F : We can think of a child object as having a virtual parent object inside the child object. In memory, a child object contains both the child fields and the parent fields. (f) X T F : In Swing, a GUI is divided into rectangular sets of pixels where each rectangular area is managed by a class that is derived from the JComponent class. (g) X T F : In Java there is no requirement that if two objects have the same hashcode, they will be equal to each other. (h) T X F : The name of an anonymous inner class should start with a capital letter. An anonymous inner class is anonymous... it has no name. (i) X T F : When Java expects a reference to a Comparator object, the compiler allows a lambda expression instead. The lambda expression arguments are the same as the arguments to compareto. (j) X T F : There is no List class in Java, just a List interface, which under the covers is implemented by many different implementations of lists, such as a LinkedList or ArrayList. Page 1 of 10
2 Answer the following questions by filling in the blanks. 2. (10 points) Given an Account class with fields ownerfirstname, ownerlastname, id, and balance, and a compareto method defined as follows: public int compareto ( Account that ) { i f ( ownerlastname. e q u a l s ( that. ownerlastname ) ) { i f ( ownerfirstname. e q u a l s ( that. ownerfirstname ) ) { return ( id that. id ) ; else { return ownerfirstname. compareto ( t h a t. ownerfirstname ) ; else { return ownerlastname. compareto ( that. ownerlastname ) ; and a tostring method defined as follows: public S t r i n g t o S t r i n g ( ) { return Acct : + id + Owner : + ownerfirstname + + ownerlastname + Balance : + S t r i n g. format ( $%.2 f, balance ) ; If printing out an array of Accounts looks like: Before s o r t : Acct : 1500 Owner : John Smith Balance : $ Acct : 1501 Owner : John Doe Balance : $ Acct : 1502 Owner : Arthur Smith Balance : $ Acct : 1503 Owner : John Smith Balance : $ Acct : 1504 Owner : Jane Doe Balance : $ And that array is an argument of the Arrays.sort method, what will get printed after the sort? After s o r t : Acct : 1504 Owner : Jane Doe Balance : $ Acct : 1501 Owner : John Doe Balance : $ Acct : 1502 Owner : Arthur Smith Balance : $ Acct : 1500 Owner : John Smith Balance : $ Acct : 1503 Owner : John Smith Balance : $ I should have asked if the array is printed after the sort, what will get printed. Need to remember Arrays.sort sorts arrays of Comparable objects by invoking compareto to determine which array element is greater than or less than other array elements, where -1 means less than, 0 means equal, and +1 means greater than. The supplied compareto method sorts on last name alphabetically, then first name, then Account number. 2 points for any answer. 5 points off for realizing a list of accounts print, but not understanding how. 1 point off for each incorrect sort. Page 2 of 10
3 3. (10 points) For the following questions, refer to the club package defined in Listing 1 on page 7, Listing 2 on page 7, Listing 3 on page 7, and Listing 4 on page 7. (a) What will get printed out to the screen if you run the main method from the ClubTester class in the club package? Rotary is meeting. The president is Jane Goodall 2 points for each line. Why did students think every member s name should appear rather than the club name? (b) What line of code in the club package demonstrates the concept of an interface used as a type, and why? In the ClubTester main method, the line stating Club rotary = new... uses the Club interface as a type. The primary reason to do this is to hide the implementation of the the club from the Tester method. There may be other ways to implement a Club, but the Tester class doesn t care (other than when creating a new instance of Club.) -2 for not specifying why. (c) (5 points (bonus)) The ArrayList toarray method can take a single argument - an array of the same type of elements as in the ArrayList. If the array in that argument is too small to fit all of the elements in the ArrayList, then the toarray method will create a larger array of the same type, and put each element of the ArrayList into this newly created array. Assuming an ArrayListClub has at least one member, will the getmembers method ever return the mems array? Why or why not? The mems array will never be returned because mems is initialized to an empty array (length of zero), which can never be big enough to hold all the elements of members (since there is at least one member). The toarray method will allocate a new array for us, and return that new array. The mems array is supplied as a template to tell toarray what kind of array to create. Page 3 of 10
4 4. (10 points) Given the Java classes in Listing 12 on page 10, Listing 13 on page 10, Listing 14 on page 10, and Listing 15 on page 10, (a) What will the BirdTester.main method print to the terminal when run? Bird Twitter has son Twitterson Duck Jemimah g o e s Quack and has son dejemimah who g o e s Quack Wren Rene s i n g s tweet t w e e t and has son Reneson whose song i s unknown (b) Notice that the coder tried to do the same thing with a wren, Wren wson = wren.sonof();, that he did with a the duck, Duck dson = duck.sonof();, but when he did so, the compiler complained that there was a type mismatch and that it could not convert a Bird to a Wren. Is this a static or dynamic type checking problem, and why? This is a problem with static type checking, because the sonof method is inherited from the Bird class, and returns a static type of Bird, which cannot be upcast to the static type of wson, which is Wren. (c) Notice that the coder tried to mimic the creation of the dson Duck object by upcasting the return value from wren.sonof() to a Wren rather than a Bird. When he did so, the code compiled, but when he ran the code, he got the run-time error message: Exception in thread main java. lang. ClassCastException : t e s t 2. Bird cannot be c a s t to t e s t 2. Wren. Is this a static or dynamic type checking problem, and why? This is an example of dynamic type checking failure. The dynamic type of the return value of wren.sonof is also Bird, because the sonof method in the Bird class returns the result of new Bird(...). The resulting object is ONLY a Bird object, and not a Bird within a Wren. (There is no song field, and just casting to Wren cannot make the song field value appear.) Sorry... I always mix up upcasting and downcasting. I should have said downcasting from the super-class to the sub-class. To avoid static type-checking, the compiler requires an explicit downcast of the result of sonof to the sub-class, Wren. However, that downcast must be based on the fact that the dynamic type of the result of sonof contains Wren. In fact, the dynamic type of the sonof method is Bird, so downcasting is invalid, as discovered at run-time. (d) In the Duck class, the coder used keyword to tell the compiler to check to make sure that the sonof method in the Duck class overrides the sonof method in the super-class, Bird. The compiler did not issue any error messages in this case, so the override was succesful, even though the sonof method returns a Bird in the Bird class, and a Duck in the Duck class. What is the relationship between Bird and Duck that makes this acceptable. Since Duck is a sub-type of Bird, in the more recent versions of Java (since Java 1.8), Java allows the use of a sub-type where a super-type is expected, even for the return type of an overriden method. This is very powerful because it allows the overriden method to return the supertype, and can then be used to dispatch methods or access public fields available for the super-type that are not allowed on the sub-type. Remember, if we change the types of the arguments, that creates a totally different method - same name, but different signature, and therefore an independent method. The amazing thing about this example is that we are allowed to change the return type, but still override the existing method! This is only possible because any user expecting the parent type result (as specified in the parent method) can still use the child type returned value BECAUSE sub-types can be used anywhere a super-type is expected. Page 4 of 10
5 5. (20 points) For the following questions, refer to the numbers package defined in Listing 5 on page 8, Listing 6 on page 8, and Listing 7 on page 8. (a) Which line or lines of code illustrated the concept of recursion in the numbers package? In the Numbers class, the gcd static method is invoked recursively if a is not equal to b. Typo alert... this was once the Numbers package, but now it has been moved into the Test2 pacakge. I should have asked in this problem s Listings on the tear off pages. (b) Will the JUnit test case defined by class NumbersTester pass or fail? If it fails, why does it fail? The JUnit test case will pass. The greatest common divisor of 12 and 33 is 3, and the lambda expression that is the second argument of the assertthrows method will throw an IllegalArgumentException. For the second test, the least commmon multiple of 12 and 33 is 132, and lcm will invoke gcd, which will throw an exception. (c) Identify all instances where the concept of first class functions is used in the test2 package, in the classes defined above. Both invocations of assertthrows in the NumbersTester class use first class functions to specify the invocation of a method which throws an exception. Also the argument to the reduce method invoked by main in the FuncStream class is a first class function - a function passed as an argument. (d) If you run the main method in the FuncReduce class, what will get printed to the screen? lcm of [28, 10, 14] is 140 lcm(28,10) = 280/gcd(28,10) = 280/2 = 140. lcm(140,14)=140*14 / gcd(140,14) = 140*14 / 14 = 140. Page 5 of 10
6 6. (10 points) The folliowing questions refer to the Java classes in Listing 8 on page 9, Listing 9 on page 9, Listing 10 on page 9, and Listing 11 on page 9. (a) Assuming the state just before the System.out.println statement in the Shapedriver main method, complete the following graphical display of memory: (b) What would get printed if you ran java -cp. test2.shapedriver? [Triangle[ 3 vertices area=6.0 ], Rectangle[ 4 vertices area=15.51 ], Rectangle[ 4 vertices area=2.0 ]] (c) The Shapes class tostring method invokes the getarea method, eve though there is no code for getarea in the Shapes class. Explain why the Java compiler allows the invocation of a method which is not defined, and why at run time, there will always be getarea method available. Since getarea is an abstract method, it forces the Shape class to be abstract, and therefore, no object of class Shape can be instantiated. A concrete child of Shape must implement getarea to be concrete, and a class must be concrete before it can be instantiated. Therefore any instantiated object which is a sub-type of Shape must have an implemented getarea method. Page 6 of 10
7 Tear-off Pages Listing 1: Person.java package club ; public class Person { S t r i n g name ; public Person ( S t r i n g name) { this. name=name ; package club ; public interface Club { void meet ( ) ; void s e t P r e s i d e n t ( Person person ) ; Person g e t P r e s i d e n t ( ) ; boolean add ( Person person ) ; Person [ ] getmembers ( ) ; Listing 2: Club.java Listing 3: ArrayListClub.java package club ; public class ArrayListClub implements Club { ArrayList<Person> members ; S t r i n g name ; Person p r e s i d e n t ; public ArrayListClub ( S t r i n g name) { this. name=name ; members=new ArrayList<Person >(); public void meet ( ) { System. out. p r i n t l n (name + i s meeting. ) ; public void s e t P r e s i d e n t ( Person person ) { p r e s i d e n t=person ; public Person g e t P r e s i d e n t ( ) { return p r e s i d e n t ; public boolean add ( Person person ) { return members. add ( person ) ; public Person [ ] getmembers ( ) { Person [ ] mems= { ; return members. toarray (mems ) ; Listing 4: ClubTester.java package club ; public class ClubTester { public static void main ( S t r i n g [ ] args ) { Club r o t a r y = new ArrayListClub ( Rotary ) ; r o t a r y. add (new Person ( John Smith ) ) ; r o t a r y. add (new Person ( Mary Black ) ) ; r o t a r y. add (new Person ( Jane Goodall ) ) ; r o t a r y. s e t P r e s i d e n t ( ( r o t a r y. getmembers ( ) ) [ 2 ] ) ; r o t a r y. meet ( ) ; System. out. p r i n t l n ( The p r e s i d e n t i s + r o t a r y. g e t P r e s i d e n t ( ). name ) ; Page 7 of 10
8 Tear-off Pages Listing 5: Numbers.java public class Numbers { static int gcd ( int a, int b ) { i f ( a<=0 b<=0) throw new IllegalArgumentException ( Arg to gcd must be p o s i t i v e ) ; i f ( a==b ) return a ; i f ( a<b ) return gcd ( a, b a ) ; return gcd ( a b, b ) ; static int lcm ( int a, int b ) { return a b / gcd ( a, b ) ; Listing 6: NumbersTester.java class NumbersTester void t e s t ( ) { a s s e r t E q u a l s ( 3, Numbers. gcd ( 1 2, 3 3 ) ) ; assertthrows ( IllegalArgumentException. class,() >Numbers. gcd (12, void t e s t l c m ( ) { a s s e r t E q u a l s (132, Numbers. lcm ( 1 2, 3 3 ) ) ; assertthrows ( IllegalArgumentException. class,() >Numbers. lcm (12, 3)); Listing 7: FuncReduce.java import java. u t i l. Arrays ; import java. u t i l. f u n c t i o n. BiFunction ; public class FuncReduce { static int reduce ( int [ ] array, BiFunction<Integer, Integer, Integer > fn, int i n i t ) { int answer=i n i t ; for ( I n t e g e r elem : array ) answer=fn. apply ( answer, elem ) ; return answer ; public static void main ( S t r i n g [ ] args ) { int [ ] v a l s= { 2 8, 1 0, 1 4 ; System. out. p r i n t l n ( lcm o f + Arrays. t o S t r i n g ( v a l s ) + i s + reduce ( vals, Numbers : : lcm, 1 ) ) ; Page 8 of 10
9 Tear-off Pages Listing 8: Shape.java public abstract class Shape { private int n ; // Number o f v e r t i c e s public Shape ( int n ) { this. n = n ; public int getn ( ) { return n ; public abstract double getarea ( ) ; public S t r i n g t o S t r i n g ( ) { return g e t C l a s s ( ). getsimplename ( ) + [ + n + v e r t i c e s area= + getarea ( ) + ] ; Listing 9: Triangle.java public class T r i a n g l e extends Shape { private double base ; private double h e i g h t ; public T r i a n g l e ( double base, double height ) { super ( 3 ) ; this. base = base ; this. h e i g h t = h e i g h t ; public double getarea ( ) { return ( base height ) / 2 ; Listing 10: Rectangle.java public class Rectangle extends Shape { private double width ; private double h e i g h t ; public Rectangle ( double width, double height ) { super ( 4 ) ; this. width = width ; this. h e i g h t = h e i g h t ; public double getarea ( ) { return width height ; Listing 11: ShapeDriver.java import java. u t i l. Arrays ; public class ShapeDriver { public static void main ( S t r i n g [ ] args ) { Shape [ ] shapes = { new T riangle ( 3. 0, 4. 0 ), new Rectangle ( 3. 3, 4. 7 ), new Rectangle ( 1. 0, 2. 0 ) ; System. out. p r i n t l n ( Arrays. t o S t r i n g ( shapes ) ) ; Page 9 of 10
10 Tear-off Pages Listing 12: Bird.java public class Bird { S t r i n g name ; public Bird ( S t r i n g name) { this. name = name ; Bird sonof ( ) { return new Bird (name+ son ) ; Listing 13: Duck.java public c l a s s Duck extends Bird { S t r i n g n o i s e ; public Duck ( S t r i n g name) { super (name ) ; n o i s e= Quack Duck sonof ( ) { return new Duck ( de +name ) ; // i t s a French duck! Listing 14: Wren.java public c l a s s Wren extends Bird { S t r i n g song ; public Wren( S t r i n g name) { super (name ) ; song= tweet tweet ; Listing 15: BirdTester.java public class BirdTester { public static void main ( S t r i n g [ ] args ) { Bird bird = new Bird ( Twitter ) ; Duck duck = new Duck ( Jemimah ) ; Wren wren = new Wren( Rene ) ; Bird bson = bird. sonof ( ) ; Duck dson = duck. sonof ( ) ; // Wren wson = (Wren) wren. sonof ( ) ; Bird wson = wren. sonof ( ) ; System. out. p r i n t l n ( Bird + bird. name + has son + bson. name ) ; System. out. p r i n t l n ( Duck + duck. name + goes + duck. n o i s e + and has son + dson. name + who goes + dson. n o i s e ) ; System. out. p r i n t l n ( Wren + wren. name + s i n g s + wren. song + and has son + wson. name + whose song i s unknown ) ; Question: Total Points: Bonus Points: Page 10 of 10
CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:
CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : If a child overrides
More informationCS-140 Fall 2017 Test 2 Version A Nov. 29, 2017
CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields
More informationBinghamton University. CS-140 Fall Dynamic Types
Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected
More 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 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 informationCS-202 Introduction to Object Oriented Programming
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction
More informationJava 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 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 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 informationCS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes
CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.
More informationCSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community
CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant
More informationCSE 143 Lecture 20. Circle
CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public
More informationCS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes
CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method
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 informationPractice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course
: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order
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 informationJava: introduction to object-oriented features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More informationCS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)
CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers
More informationpublic static boolean isoutside(int min, int max, int value)
See the 2 APIs attached at the end of this worksheet. 1. Methods: Javadoc Complete the Javadoc comments for the following two methods from the API: (a) / @param @param @param @return @pre. / public static
More informationAgenda. Objects and classes Encapsulation and information hiding Documentation Packages
Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics
More informationUMBC CMSC 331 Final Exam
UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy
More informationCS 251 Intermediate Programming Inheritance
CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?
More information24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini
24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationB2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA
B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE
More informationFirst Name: AITI 2004: Exam 2 July 19, 2004
First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: JSP Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand
More informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationInheritance and Interfaces
Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical
More informationWhat is Inheritance?
Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting
More information25. Generic Programming
25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and
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 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 informationType Hierarchy. Lecture 6: OOP, autumn 2003
Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at
More informationDeclarations 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 informationLanguage 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 informationQUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March
QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March 2006 11.05-12.35 Please fill in your Examination Number here: Student Number here: MODEL ANSWERS All
More informationCS/ENGRD 2110 SPRING 2018
CS/ENGRD 2110 SPRING 2018 Lecture 7: Interfaces and http://courses.cs.cornell.edu/cs2110 1 2 St Valentine s Day! It's Valentines Day, and so fine! Good wishes to you I consign.* But since you're my students,
More informationAbstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.
a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must
More informationCompaq Interview Questions And Answers
Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not
More informationChapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,
Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design
More 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 Motivation
Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life
More information22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming
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 informationInheritance (continued) Inheritance
Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses
More informationMaking New instances of Classes
Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using
More informationLecture Notes Chapter #9_b Inheritance & Polymorphism
Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1
More 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 informationINHERITANCE. Spring 2019
INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose
More informationOverview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting
Overview ITI 1121. Introduction to Computing II Rafael Falcon and Marcel Turcotte (with contributions from R. Holte) Electrical Engineering and Computer Science University of Ottawa Interface Abstract
More informationCS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces
CS 112 Programming 2 Lecture 10 Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces 2 1 Motivations We have learned how to write simple programs to create and display GUI components.
More informationInheritance and Polymorphism
Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html
More 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 informationSelected Java Topics
Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings
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 informationChapter 6: Inheritance
Chapter 6: Inheritance EECS 1030 moodle.yorku.ca State of an object final int WIDTH = 3; final int HEIGTH = 4; final int WEIGHT = 80; GoldenRectangle rectangle = new GoldenRectangle(WIDTH, HEIGHT, WEIGHT);
More informationInheritance, polymorphism, interfaces
Inheritance, polymorphism, interfaces "is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a
More informationOBJECT ORİENTATİON ENCAPSULATİON
OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual
More informationObject Oriented Programming 2015/16. Final Exam June 28, 2016
Object Oriented Programming 2015/16 Final Exam June 28, 2016 Directions (read carefully): CLEARLY print your name and ID on every page. The exam contains 8 pages divided into 4 parts. Make sure you have
More informationFor this section, we will implement a class with only non-static features, that represents a rectangle
For this section, we will implement a class with only non-static features, that represents a rectangle 2 As in the last lecture, the class declaration starts by specifying the class name public class Rectangle
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationMore on Objects in JAVA TM
More on Objects in JAVA TM Inheritance : Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a
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 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 informationXC Total Max Score Grader
NAME: NETID: CS2110 Fall 2013, Prelim 1 Thursday Oct 10, 2013 (7:30-9:00p) The exam is closed book and closed notes. Do not begin until instructed. You have 90 minutes. Good luck! Write your name and Cornell
More informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
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 informationCollections, Maps and Generics
Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.
More informationCISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College
CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype
More informationInheritance. Lecture 11 COP 3252 Summer May 25, 2017
Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data
More informationRelationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor
CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog
More informationCSIS 10B Lab 2 Bags and Stacks
CSIS 10B Lab 2 Bags and Stacks Part A Bags and Inheritance In this part of the lab we will be exploring the use of the Bag ADT to manage quantities of data of a certain generic type (listed as T in the
More informationCS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.
Methods There s a method in my madness. Sect. 3.3, 8.2 1 Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer
More informationInheritance and Interfaces
Inheritance and Interfaces what is inheritance? examples & Java API examples inheriting a method overriding a method polymorphism Object tostring interfaces Ex: sorting and Comparable interface Inheritance
More informationBinghamton University. CS-140 Fall Functional Java
Functional Java 1 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data
More informationINHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U
C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes
More informationRelationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.
CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches
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 informationCS1150 Principles of Computer Science Objects and Classes
CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8
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 informationName Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?
1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationRelationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor
CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog
More informationFirst Name: AITI 2004: Exam 2 July 19, 2004
First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: Standard Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand
More informationPrograms as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects
CS256 Computer Science I Kevin Sahr, PhD Lecture 11: Objects 1 Programs as Models remember: we write programs to solve realworld problems programs act as models of the real-world problem to be solved one
More informationAdvanced Placement Computer Science. Inheritance and Polymorphism
Advanced Placement Computer Science Inheritance and Polymorphism What s past is prologue. Don t write it twice write it once and reuse it. Mike Scott The University of Texas at Austin Inheritance, Polymorphism,
More informationJava Review. Fundamentals of Computer Science
Java Review Fundamentals of Computer Science Link to Head First pdf File https://zimslifeintcs.files.wordpress.com/2011/12/h ead-first-java-2nd-edition.pdf Outline Data Types Arrays Boolean Expressions
More informationFramework Fundamentals
Questions Framework Fundamentals 1. Which of the following are value types? (Choose all that apply.) A. Decimal B. String C. System.Drawing.Point D. Integer 2. Which is the correct declaration for a nullable
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 informationCSC207 Week 3. Larry Zhang
CSC207 Week 3 Larry Zhang 1 Announcements Readings will be posted before the lecture Lab 1 marks available in your repo 1 point for creating the correct project. 1 point for creating the correct classes.
More informationCOE318 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 informationMore About Objects. Zheng-Liang Lu Java Programming 255 / 282
More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism
More informationAPCS Semester #1 Final Exam Practice Problems
Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester
More informationCOMP 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 informationChapter 2: Java OO II X I A N G Z H A N G
Chapter 2: Java OO II X I A N G Z H A N G j a v a c o s e @ q q. c o m Content 2 Abstraction Abstract Class Interface Inheritance Polymorphism Abstraction What is Abstraction? Abstraction 4 An abstraction
More informationCSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014
CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 Name: This exam consists of 5 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet
More informationBinghamton University. CS-140 Fall Problem Solving. Creating a class from scratch
Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods
More informationCMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.
CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object
More informationUnit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW
Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy
More information