Cloning Enums. Cloning and Enums BIU OOP

Size: px
Start display at page:

Download "Cloning Enums. Cloning and Enums BIU OOP"

Transcription

1

2 Table of contents 1 Cloning 2 Integer representation Object representation Java Enum

3 Cloning

4 Objective We have an object and we need to make a copy of it. We need to choose if we want a shallow copy or a deep copy.

5 Shallow VS Deep Shallow copy Copy primitive members values. Copy the references to objects (Referenced objects will not be duplicated). Deep copy Copy primitive members values. Create copies of referenced objects (Referenced objects will be duplicated).

6 Motivation Example object Class Diagram:

7 Motivation Example object Class Diagram: Question How can we create a copy of an existing Professional object?

8 Method 1 - Method Special constructor that receives the same class type. Copy all the values as we initialize the new object.

9 Method 1 - Method Special constructor that receives the same class type. Copy all the values as we initialize the new object. Simple class (only primitives and no inheritance) 3 public class Person { 4 5 private String firstname ; 6 private String lastname ; public Person ( Person other ) { 19 this. firstname = other. firstname ; 20 this. lastname = other. lastname ; 21 } }

10 Method 1 - (2) Method Special constructor that receives the same class type. Copy all the values as we initialize the new object. Complex class (contains references and is a subclass) 3 public class Professional extends Person { 4 5 private int yearsofexperience ; 6 private Diploma diploma ; public Professional ( Professional other ) { 22 super ( other ); this. yearsofexperience = other. yearsofexperience ; 25 // deep copy of diploma 26 this. diploma = new Diploma ( other. diploma ); 27 } }

11 Method 1 - (3) Pros Fast. Simple to implement.

12 Method 1 - (3) Pros Fast. Simple to implement. Cons Assumes s available for super classes. Need to know the exact type during cloning.

13 Method 2 - Method A method that returns a copy of the object.

14 Method 2 - Method A method that returns a copy of the object. Simple class (only primitives and no inheritance) 3 public class Person { 4 5 private String firstname ; 6 private String lastname ; public Person copy (){ 14 return new Person ( getfirstname (), getlastname ()); 15 } }

15 Method 2 - (2) Method A method that returns a copy of the object.

16 Method 2 - (2) Method A method that returns a copy of the object. Complex class (contains references and is a subclass) 3 public class Professional extends Person { 4 5 private int yearsofexperience ; 6 private Diploma diploma ; public Professional copy (){ 16 return new Professional ( 17 getfirstname (), 18 getlastname (), 19 getyearsofexperience (), 20 getdiploma (). copy () // deep copy 21 ); 22 } }

17 Method 2 - (3) Pros Simple to implement. Don t have to know the exact type of object to copy it.

18 Method 2 - (3) Pros Simple to implement. Don t have to know the exact type of object to copy it. Cons Can t reuse the copy() implementation of the super class. Slower than the copy constructor. Additional method call is required.

19 Method 3 - Method A special method that preforms an efficient shallow copy.

20 Method 3 - Method A special method that preforms an efficient shallow copy. 1 public class Object { protected native () throws CloneNotSupportedException ; } How to use? 1 Override the method in your implementation. 2 Change method visibility to public (instead of protected). 3 implement the empty interface Cloneable. 4 call super.clone() for shallow copy. 5 Manually set non primitive fields if deep copy is required.

21 Method 3 - (2) Method A special method that preforms an efficient shallow copy. Simple class (only primitives and no inheritance) 3 public class Person implements Cloneable { 4 5 private String firstname ; 6 private String lastname ; public Person clone () { 23 try { 24 return ( Person ) super. clone (); 25 } catch ( CloneNotSupportedException e) { 26 throw new AssertionError (" Failed cloning Person "); 27 } 28 } 29 }

22 Method 3 - (3) Method A special method that preforms an efficient shallow copy. Complex class (contains references and is a subclass) 3 public class Professional extends Person implements Cloneable { 4 5 private int yearsofexperience ; 6 private Diploma diploma ; public Professional clone () { 25 Professional copy = ( Professional ) super. clone (); 26 copy. diploma = this. diploma. clone (); // deep copy 27 return copy ; 28 } }

23 Method 3 - (4) Pros Fastest for shallow copy or classes with many primitives. Don t have to know the exact type of object to copy it.

24 Method 3 - (4) Pros Fastest for shallow copy or classes with many primitives. Don t have to know the exact type of object to copy it. Cons Complex implementation, easy to forget something. Not necessary faster for deep copy. All classes in inheritance hierarchy must implement Cloneable. Constructor of copied objects is not called. (Can cause logical problems in your implementation)

25 Cloning Summary No single best solution. Avoid unless optimization is really needed. Use copy method if performance is not an issue because it s most flexible.

26 Cloning Summary Note No single best solution. Avoid unless optimization is really needed. Use copy method if performance is not an issue because it s most flexible. The copy method approach is also known as the Prototype creational design pattern.

27 Integer representation Object representation Java Enum

28 Integer representation Object representation Java Enum Objective We need to create a type that has a small number of possible assignments. We want to minimize the risk of assigning values that have no meaning. Example: The days of the week: Sunday, Monday,...

29 Integer representation Object representation Java Enum Solution 1 - Represent as Integer Definition 6 public class WeekDay { 7 8 public static final int SUNDAY = 0; 9 public static final int MONDAY = 1; 10 public static final int TUESDAY = 2; 11 public static final int WEDNESDAY = 3; 12 public static final int THURSDAY = 4; 13 public static final int FRIDAY = 5; 14 public static final int SATURDAY = 6; } Usage 8 int day = WeekDay. SATURDAY ; 9 10 // simple equality 11 if( WeekDay. FRIDAY == day ) { 12 System.out. println ("The day is Friday "); 13 }

30 Integer representation Object representation Java Enum Solution 1 - Represent as Integer (2) Operations 6 public class WeekDay { public static int nextday ( int weekday ) { 30 return ( weekday + 1) % 7; 31 } } Usage 16 int nextday = WeekDay. nextday (day ); System.out. println (" Actual day name :" + WeekDay. tostring (day )); 19 System.out. println ("Next day name :" + WeekDay. tostring ( nextday ));

31 Integer representation Object representation Java Enum Solution 1 - Represent as Integer (3) Cons Type is unclear from reading the code (uses int but means something else). No type safety, can accidentally hold an invalid value (out of meaningful range). Type operations are global (as static methods), not really object oriented.

32 Integer representation Object representation Java Enum Solution 2 - Objects & Exceptions Definition 6 public class WeekDay { 7 8 public static final int SUNDAY_INDEX = 0; 9 public static final int MONDAY_INDEX = 1; 10 public static final int TUESDAY_INDEX = 2; 11 public static final int WEDNESDAY_INDEX = 3; 12 public static final int THURSDAY_INDEX = 4; 13 public static final int FRIDAY_INDEX = 5; 14 public static final int SATURDAY_INDEX = 6; private int index ; public WeekDay ( int index ) { 19 if( index > 6 index < 0) { 20 throw new IllegalArgumentException (" Weekday index must be in range 0-6, provided :" + index ); 21 } this. index = index ; 24 } }

33 Integer representation Object representation Java Enum Solution 2 - Objects & Exceptions (2) Operations 26 public WeekDay nextday () { 27 return new WeekDay (( this. index + 1) % 7); 28 } Usage 11 if( WeekDay. FRIDAY_INDEX == day. getindex ()) { 12 System.out. println ("The day is Friday "); 13 } // operations on type 16 WeekDay nextday = day. nextday (); System.out. println (" Actual day name :" + day ); 19 System.out. println ("Next day name :" + nextday ); 20 } }

34 Integer representation Object representation Java Enum Solution 2 - Objects & Exceptions (3) Pros Clear Type, easier reading. Operations as methods.

35 Integer representation Object representation Java Enum Solution 2 - Objects & Exceptions (3) Pros Clear Type, easier reading. Operations as methods. Cons Type safety only at Runtime (through RuntimeException). Need to use equals() for comparing with another object. Comparing with literal through value of getter. User is aware that internal representation is via an integer index. (Encapsulation is broken)

36 Integer representation Object representation Java Enum Solution 3 - Objects & Singleton Values Definition 7 public class WeekDay { 8 9 public static final WeekDay SUNDAY = new WeekDay (0) ; 10 public static final WeekDay MONDAY = new WeekDay (1) ; 11 public static final WeekDay TUESDAY = new WeekDay (2) ; 12 public static final WeekDay WEDNESDAY = new WeekDay (3) ; 13 public static final WeekDay THURSDAY = new WeekDay (4) ; 14 public static final WeekDay FRIDAY = new WeekDay (5) ; 15 public static final WeekDay SATURDAY = new WeekDay (6) ; private WeekDay ( int index ) { 30 this. index = index ; 31 } }

37 Integer representation Object representation Java Enum Solution 3 - Objects & Singleton Values (2) Operations 7 public class WeekDay { private static final WeekDay [] values = new WeekDay []{ 18 SUNDAY, 19 MONDAY, 20 TUESDAY, 21 WEDNESDAY, 22 THURSDAY, 23 FRIDAY, 24 SATURDAY 25 }; public WeekDay nextday () { 34 return values [( this. index + 1) % 7]; 35 } }

38 Integer representation Object representation Java Enum Solution 3 - Objects & Singleton Values (3) Usage 8 WeekDay day = WeekDay. SUNDAY ; 9 10 // equality 11 if( WeekDay. FRIDAY == day ) { 12 System.out. println ("The day is Friday "); 13 } // operations on type 16 WeekDay nextday = day. nextday (); System.out. println (" Actual day name :" + day ); 19 System.out. println ("Next day name :" + nextday );

39 Integer representation Object representation Java Enum Solution 3 - Objects & Singleton Value (4) Pros Clear Type, easier reading. Operations as methods. Full Type safety. Comparison using the == operator. Internal structure is completely hidden from the user.

40 Integer representation Object representation Java Enum Solution 3 - Objects & Singleton Value (4) Pros Clear Type, easier reading. Operations as methods. Full Type safety. Comparison using the == operator. Internal structure is completely hidden from the user. Cons - Minimal! Must implement equals()/hashcode() to be used in Collections. Can t be used in a switch case. Note This is an excellent solution for other object oriented languages that don t have a special enum type.

41 Integer representation Object representation Java Enum Solution 4 - Java Enum Definition 6 public enum WeekDay { 7 8 SUNDAY (" Sunday "), 9 MONDAY (" Monday "), 10 TUESDAY (" Tuesday "), 11 WEDNESDAY (" Wednesday "), 12 THURSDAY (" Thursday "), 13 FRIDAY (" Friday "), 14 SATURDAY (" Saturday "); private String stringrepresentation ; private WeekDay ( String stringrepresentation ) { 19 this. stringrepresentation = stringrepresentation ; 20 } }

42 Integer representation Object representation Java Enum Solution 4 - Java Enum (2) Operations 6 public enum WeekDay { public WeekDay nextday () { 23 return values () [( this. ordinal () + 1) % 7]; 24 } public WeekDay previousday () { 27 return values () [( this. ordinal () + 6) % 7]; 28 } public String tostring () { 32 return this. stringrepresentation ; 33 } }

43 Integer representation Object representation Java Enum Solution 4 - Java Enum (3) Usage 11 WeekDay day = WeekDay. SUNDAY ; // equality 14 if( WeekDay. FRIDAY == day ) { 15 System.out. println ("The day is Friday "); 16 } // operations on type 19 WeekDay nextday = day. nextday (); System.out. println (" Actual day name :" + day ); 22 System.out. println ("Next day name :" + nextday );

44 Integer representation Object representation Java Enum Solution 4 - Java Enum (4) Pros All the advantages of the previous solution. Can be used with a switch case statement. Has super efficient EnumSet implementation (as a bit mask). Has super efficient EnumMap implementation for Enum keys.

45 Integer representation Object representation Java Enum Solution 4 - Java Enum (4) Pros All the advantages of the previous solution. Can be used with a switch case statement. Has super efficient EnumSet implementation (as a bit mask). Has super efficient EnumMap implementation for Enum keys. Example 25 Set <WeekDay > workdays = EnumSet.of( 26 WeekDay. SUNDAY, WeekDay. MONDAY, WeekDay. TUESDAY, WeekDay. WEDNESDAY, WeekDay. THURSDAY 27 ); // super fast set operations ( set stored as bit array ) 30 if( workdays. contains (day )){ 31 System.out. println (" Better get to work "); 32 }

46 Integer representation Object representation Java Enum Enum Summary Avoid using primitives to represent types that only have a small range of possible values. make the code clear and enforce safety. (and enum collections) are very efficient at run time.

47 Integer representation Object representation Java Enum Enum Summary Note Avoid using primitives to represent types that only have a small range of possible values. make the code clear and enforce safety. (and enum collections) are very efficient at run time. The Objects + Singleton Values approach provides most of the functionality and can be very useful to emulate enum behaviour in languages that don t provide an enum type.

48 Integer representation Object representation Java Enum Summary 1 Cloning 2 Integer representation Object representation Java Enum

The Object clone() Method

The Object clone() Method The Object clone() Method Introduction In this article from my free Java 8 course, I will be discussing the Java Object clone() method. The clone() method is defined in class Object which is the superclass

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

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Inheritance A form of software reuse in which a new class is created by absorbing an existing class s members and enriching them with

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns Tecniche di Progettazione: Design Patterns GoF: Memento Prototype Visitor 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Memento 2 Design patterns, Laura Semini, Università

More information

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double(3.14); 4... Zheng-Liang Lu Java Programming 290 / 321 Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation

More information

Agenda: Discussion Week 7. May 11, 2009

Agenda: Discussion Week 7. May 11, 2009 Agenda: Discussion Week 7 Method signatures Static vs. instance compareto Exceptions Interfaces 2 D arrays Recursion varargs enum Suggestions? May 11, 2009 Method signatures [protection] [static] [return

More information

Timing for Interfaces and Abstract Classes

Timing for Interfaces and Abstract Classes Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

CS 113 PRACTICE FINAL

CS 113 PRACTICE FINAL CS 113 PRACTICE FINAL There are 13 questions on this test. The value of each question is: 1-10 multiple choice (4 pt) 11-13 coding problems (20 pt) You may get partial credit for questions 11-13. If you

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

Lecture 12. Data Types and Strings

Lecture 12. Data Types and Strings Lecture 12 Data Types and Strings Class v. Object A Class represents the generic description of a type. An Object represents a specific instance of the type. Video Game=>Class, WoW=>Instance Members of

More information

Exceptions and Design

Exceptions and Design Exceptions and Exceptions and Table of contents 1 Error Handling Overview Exceptions RuntimeExceptions 2 Exceptions and Overview Exceptions RuntimeExceptions Exceptions Exceptions and Overview Exceptions

More information

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects Administrative Stuff September 12, 2007 HW3 is due on Friday No new HW will be out this week Next Tuesday we will have Midterm 1: Sep 18 @ 6:30 7:45pm. Location: Curtiss Hall 127 (classroom) On Monday

More information

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester Programming Language Control Structures: Selection (switch) Eng. Anis Nazer First Semester 2018-2019 Multiple selection choose one of two things if/else choose one from many things multiple selection using

More information

Chapter 8: A Second Look at Classes and Objects

Chapter 8: A Second Look at Classes and Objects Chapter 8: A Second Look at Classes and Objects Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 8 discusses the following main topics:

More information

Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces Chapter 13 Abstract Classes and Interfaces 1 Abstract Classes Abstraction is to extract common behaviors/properties into a higher level in the class hierarch so that they are shared (implemented) by subclasses

More information

public Candy() { ingredients = new ArrayList<String>(); ingredients.add("sugar");

public Candy() { ingredients = new ArrayList<String>(); ingredients.add(sugar); Cloning Just like the name implies, cloning is making a copy of something. To be true to the nature of cloning, it should be an exact copy. While this can be very useful, it is not always necessary. For

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #13: Java OO cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Homework due next week Problem #2 revisited Constructors, revisited Remember: a

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

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

More information

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University Enumerated Types CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Enumerated Types An enumerated type defines a list of enumerated values Each value is an identifier

More information

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

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

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with

More information

Objectives. Describe ways to create constants const readonly enum

Objectives. Describe ways to create constants const readonly enum Constants Objectives Describe ways to create constants const readonly enum 2 Motivation Idea of constant is useful makes programs more readable allows more compile time error checking 3 Const Keyword const

More information

CS 251 Intermediate Programming More on classes

CS 251 Intermediate Programming More on classes CS 251 Intermediate Programming More on classes Brooke Chenoweth University of New Mexico Spring 2018 Empty Class public class EmptyClass { Has inherited methods and fields from parent (in this case, Object)

More information

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax

Tirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax Tirgul 1 Today s topics: Course s details and guidelines. Java reminders and additions: Packages Inner classes Command Line rguments Primitive and Reference Data Types Guidelines and overview of exercise

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Chapter 4 Defining Classes I

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

to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or

to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or Prototype Intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype Applicability Use the Prototype pattern when a system should be independent

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

BBM 102 Introduction to Programming II Spring Inheritance

BBM 102 Introduction to Programming II Spring Inheritance BBM 102 Introduction to Programming II Spring 2018 Inheritance 1 Today Inheritance Notion of subclasses and superclasses protected members UML Class Diagrams for inheritance 2 Inheritance A form of software

More information

Interview Questions I received in 2017 and 2018

Interview Questions I received in 2017 and 2018 Interview Questions I received in 2017 and 2018 Table of Contents INTERVIEW QUESTIONS I RECEIVED IN 2017 AND 2018... 1 1 OOPS... 3 1. What is the difference between Abstract and Interface in Java8?...

More information

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

More on Objects in JAVA TM

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

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Strings and Enumerations 2018W (Institute of Pervasive Computing, JKU Linz) CHARACTER ENCODING On digital systems, each character is represented by a specific number. The character

More information

Week 7 Inheritance. Written by Alexandros Evangelidis. Adapted from Joseph Gardiner. 10 November 2015

Week 7 Inheritance. Written by Alexandros Evangelidis. Adapted from Joseph Gardiner. 10 November 2015 Week 7 Inheritance Written by Alexandros Evangelidis. Adapted from Joseph Gardiner 10 November 2015 1 This Week By the end of the tutorial, we should have covered: Inheritance What is inheritance? How

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis Principles of Software Construction: Objects, Design, and Concurrency Objects (continued) toad Spring 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 J Aldrich and W Scherlis Announcements

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

List ADT. Announcements. The List interface. Implementing the List ADT

List ADT. Announcements. The List interface. Implementing the List ADT Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as

More information

CSC-140 Assignment 6

CSC-140 Assignment 6 CSC-140 Assignment 6 1 Introduction In this assignment we will start out defining our own classes. For now, we will design a class that represents a date, e.g., Tuesday, March 15, 2011, or in short hand

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

CISC370: Inheritance

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

Chapter 2: Objects and Primitive Data

Chapter 2: Objects and Primitive Data Chapter 2: Objects and Primitive Data Multiple Choice 1. c 2. e 3. d 4. b 5. a 6. e 7. b 8. c 9. d 10. b True/False 1. T 2. F 3. T 4. T 5. T 6. F 7. T 8. T Short Answer 2.1. Explain the following programming

More information

A Model of Mutation in Java

A Model of Mutation in Java Object-Oriented Design Lecture 18 CSU 370 Fall 2008 (Pucella) Friday, Nov 21, 2008 A Model of Mutation in Java We have been avoiding mutations until now; but there are there, in the Java system, for better

More information

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students.  Collections. Play with problem set 1 Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen Other conditional and loop constructs Fundamentals of Computer Science Keith Vertanen Overview Current loop constructs: for, while, do-while New loop constructs Get out of loop early: break Skip rest of

More information

Chapter 5 Object-Oriented Programming

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

TYPES, VALUES AND DECLARATIONS

TYPES, VALUES AND DECLARATIONS COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1 Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier

More information

Chapter 4: Writing Classes

Chapter 4: Writing Classes Chapter 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Writing Classes We've been using predefined classes. Now we will learn to write our own

More information

Announcements/Follow-ups

Announcements/Follow-ups Announcements/Follow-ups Midterm #2 Friday Everything up to and including today Review section tomorrow Study set # 6 online answers posted later today P5 due next Tuesday A good way to study Style omit

More information

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG.

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG. Comp435 Object-Oriented Design Week 11 Computer Science PSU HBG 1 Define an interface for creating an object Let subclasses decide which class to instantiate Defer instantiation to subclasses Avoid the

More information

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

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

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

C R E A T I V E A C A D E M Y. Web Development. Photography

C R E A T I V E A C A D E M Y. Web Development. Photography CE C R E A T I V E A C A D E M Y Graphic Design Web Design Web Development Photography ACE CREATIVE ACADEMY [ACA] is a Lagos based creative academy that trains individuals to have all the skills and knowledge

More information

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

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff Outline 1 Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables: protected Inheritance and constructors, super The is-a vs. has-a relationship (Inheritance

More information

Shallow Copy vs. Deep Copy

Shallow Copy vs. Deep Copy Shallow Copy vs. Deep Copy Introduction In this article from my free Java 8 Course, I will be discussing the difference between a Deep and a Shallow Copy. What is a Copy? To begin, I d like to highlight

More information

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable. Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2008 January Exam Question Max Internal

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Inheritance and Interfaces

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

Introduction to Programming

Introduction to Programming Introduction to Programming René Thiemann Institute of Computer Science University of Innsbruck WS 2008/2009 RT (ICS @ UIBK) Chapter 3 1/32 Outline Foundations of Object Orientation Data hiding RT (ICS

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

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object Review: Diagrams for Inheritance - String makemodel - int mileage + (String, int) Class #3: Inheritance & Polymorphism Software Design II (CS 220): M. Allen, 25 Jan. 18 + (String, int) + void

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

Chapter 11 Classes Continued

Chapter 11 Classes Continued Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.

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

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing. CISC-124 20180115 20180116 20180118 We continued our introductory exploration of Java and object-oriented programming by looking at a program that uses two classes. We created a Java file Dog.java and

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

Tecniche di Progettazione: Design Patterns

Tecniche di Progettazione: Design Patterns Tecniche di Progettazione: Design Patterns GoF: Mediator Memento Prototype 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Mediator 2 Design patterns, Laura Semini, Università

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

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 17 Inheritance Overview Problem: Can we create bigger classes from smaller ones without having to repeat information? Subclasses: a class inherits

More information

Software Design Patterns. Aliaksei Syrel

Software Design Patterns. Aliaksei Syrel Software Design Patterns Aliaksei Syrel 1 Pattern types Creational Patterns Behavioural Patterns Structural Patterns 2 Creational Patterns Creational design patterns deal with object creation mechanisms,

More information

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance CS257 Computer Science I Kevin Sahr, PhD Lecture 10: Inheritance 1 Object Oriented Features For a programming language to be called object oriented it should support the following features: 1. objects:

More information

COMP 401 COPY: SHALLOW AND DEEP. Instructor: Prasun Dewan

COMP 401 COPY: SHALLOW AND DEEP. Instructor: Prasun Dewan COMP 401 COPY: SHALLOW AND DEEP Instructor: Prasun Dewan PREREQUISITE Composite Object Shapes Inheritance 2 CLONE SEMANTICS? tostring() Object equals() clone() Need to understand memory representation

More information

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

Converting Collections to Arrays. A Bad Approach to Array Conversion. A Better Approach to Array Conversion. public Object[] toarray();

Converting Collections to Arrays. A Bad Approach to Array Conversion. A Better Approach to Array Conversion. public Object[] toarray(); Converting Collections to Arrays Every Java collection can be converted to an array This is part of the basic Collection interface The most elementary form of this method produces an array of base-type

More information

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Review sheet for Final Exam (List of objectives for this course)

Review sheet for Final Exam (List of objectives for this course) Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

Testing Object-Oriented Software. COMP 4004 Fall Notes Adapted from Dr. A. Williams

Testing Object-Oriented Software. COMP 4004 Fall Notes Adapted from Dr. A. Williams Testing Object-Oriented Software COMP 4004 Fall 2008 Notes Adapted from Dr. A. Williams Dr. A. Williams, Fall 2008 Software Quality Assurance Lec 9 1 Testing Object-Oriented Software Relevant characteristics

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

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

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018 Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside

More information

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class Motivations Chapter 13 Abstract Classes and Interfaces You have learned how to write simple programs to create and display GUI components. Can you write the code to respond to user actions, such as clicking

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

Software Construction

Software Construction Lecture 7: Type Hierarchy, Iteration Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering

More information

SSE3052: Embedded Systems Practice

SSE3052: Embedded Systems Practice SSE3052: Embedded Systems Practice Minwoo Ahn minwoo.ahn@csl.skku.edu Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information