Exercises Software Development I. 08 Objects II. Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014
|
|
- Gerard Poole
- 6 years ago
- Views:
Transcription
1 Exercises Software Development I 08 Objects II Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute for Pervasive Computing Johannes Kepler University Linz riener@pervasive.jku.at
2 Classes and Objects: State of Objects Variable/Object Types Primitive variables (static or class variables) Object variables - A container for objects; to such variables objects can be assigned to, i.e., a variable of type from any class Example: Person p; - The opposite of object variables are primitive variables, e.g. int age; - Default initial state defined at time of object creation with new Operator e.g., new ObjectName(); specified by default initial state of all variables contained in that object ( s description) Member variables, instance variables - Synonym use of these two terms - A variable declared within a class and which is created every time the class is instantiated - Can be either modified by method invocation (=call) or direct (should be avoided data encapsulation ) Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 2
3 Classes and Objects: Generating Objects Basics: Consider the following statement ObjectName myobject = new ObjectName(); What exactly is 'new ObjectName()';??? a function/method call? Each and every class defines at least one constructor method name of the constructor equals the name of the class Standard constructor: no parameters, no specific (variable) initialization automatically generated by Java (but can me overwritten) What happens during object generation? Processing of 'new' creates a dynamic instance of the class, e.g. instantiation provides an object of that class with all the member attributes (One of) the constructor(s) of the class is called, the just created object is implicitely pased to this constructor (using the this reference; see later) Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 3
4 Classes and Objects: Generating Objects Example: Different options to instantiate a new 'Person' object Option 1 (call it the bad ) Person pbad = new Person(); pbad.name = "Michael"; pbad.age = 21; Option 2 ( the better ) Person pbetter = new Person(); pbetter.setname("michael"); pbetter.setage(21); Option 3 ( the best ) Person pbest = new Person("Michael", 21); self defined constructor with 2 parameters (String, int) proper constructor selected during object generation; if no constructor is specified and no parameters are passed, a standard constructor will be created and used) Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 4
5 Classes and Objects: Generating Objects What is a constructor; what is its function? Constructors are sort of special methods that are used to define (assign) the initial state of objects Constructors are always named after the class, i.e., constructors of the class Person are named Person(...) Constructors never have a return type, i.e., they do not allow to return results to the caller no return type means: nothing, not even void implicitly, the constructor has a return type; it returns an instance (an object) of the class It is possible to define more than one constructor per class differentiation by number and/or data types of the parameters (also the order of parameters is used to differentiate between similar constructors) this concept is called constructor overloading Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 5
6 I Classes and Objects: Generating Objects Types of constructors Default constructor ObjectName(); this constructor is automatically created by the Java compiler (javac) might be overwritten by the programmer (in this case, the compiler does not create another one implicitly) creates an object in its initial (default) state; every object contained in the just created object will also be generated and initialized in its default state, e.g., public class Flat { int norooms; int sqmeters; Person owner; public Flat() { norooms = 2; owner = new Person(); public class Person { String name; float rate; // Eur/sqm public Person() { name = ""; rate = 7.5f; Flat myflat = new Flat(); System.out.println(myFlat.owner.rate); // value? 7.5 Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 6
7 I Classes and Objects: Generating Objects Types of constructors Copy constructor ObjectName(ObjectName o); creates a new object as copy of the object 'o' field-by-field assignment has to be implemented by the programmer (no standard concept) Don t confuse with the clone()-concept defined in class Object (see later) Special constructor ObjectName(DataType1 para1,...); any number of constructors similar (same) name, but have to be unique: (1) number of parameters (2) data types of parameters (3) order of parameter list! public Flat(int sqmeters, Person owner); public Flat(Person owner, int sqmeters); Two different constructors: Differentiated by the order of parameters (data types) Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 7
8 Classes and Objects: Generating Objects Usage example (correct) public class Person { private String name; private int age; // overwritten default constructor // assigns standard values to all member variables public Person () { name = ""; age = 0; //... // general constructor with two parameters 's', 'i public Person (String s, int i) { name = s; // initialize name with value given in 's' age = i; // initialize age with value given in 'i' Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 8
9 Classes and Objects: Generating Objects Usage example (correct) public class Person { private String name, phone; private int age, weight, height; private int birthd, birthm, birthy; private int svn; Ok works, but hard to read here... Parameter semantics cannot be determined/derived from parameter names Ok, why not using descriptive parameter names: 'name', 'phone', 'age', etc.? // overwritten default constructor // assigns standard values to all member variables public Person () { name = ""; age = 0, weight = 0, height = 0, birthd= 0, birthm = 0, birthy = 0; // general constructor with many parameters public Person (String s, String p, int a, int b, int c, int d, int e, int f ) { name = s; // initialize name with value given in 's' phone = p; // initialize phone with value given in 'p' age = a; // initialize age with value given in 'a' birthd = b; // initialize birth day with value given in 'b' birthm = c; // initialize birth month with value given in 'c'... Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 9
10 Classes and Objects: Generating Objects Usage example (faulty) public class Person { private String name, phone; private int age; // overwritten default constructor // assigns standard values to all member variables public Person () { name = ""; phone = ""; age = 0; //...!??? // general constructor with two parameters 'name', 'age' public Person (String name, int age) { name = name; age = age;??? Which attributes are meant here? Instance variables or parameter? Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 10
11 Classes and Objects: Generating Objects - Constructors How to solve the problem of duplicate identifiers (in the constructor)? Use the reference operator 'this' 'this' is a special instance variable that is defined (can be used) within methods of an object [during method invocation] is a container for instance variables whose method or constructor is currently executed can be used like any other normal instance variable solves the problem of similar names (i.e., parameter or local variable overloading object variables) this concept allows to address/identify member attributes always correctly Usage example (correct, using this-reference) public class Person { private String name; private int age; // general constructor with two parameters 'name', 'age' public Person (String name, int age) { this.name = name; this.age = age; Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 11
12 Classes and Objects: Generating Objects this-reference: Demonstration example - class Person public class Person { private String name; private String phone; private int age; public Person(String name, String phone, int age){ this.name = name; this.phone = phone; this.age = age; public void printpersondetails() { System.out.println(this.name + " (" + this.age + " years): " + this.phone); public static void main (String[] args) { Person instructor = new Person ("Andreas Riener", " ", 55); Person student = new Person ("Bart Simpson", " ", 18); Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 13
13 Classes and Objects: Generating Objects this-reference: Demonstration example - class Person public class Person { private String name; private String phone; private int age; public Person(String name, String phone, int age){ this.name = name; this.phone = phone; this.age = age; public void printpersondetails() { System.out.println(this.name + " (" + this.age + " years): " + this.phone); public static void main (String[] args) { Person instructor = new Person ("Andreas Riener", " ", 55); Person student = new Person ("Bart Simpson", " ", 18); instructor.printpersondetails(); student.printpersondetails(); Andreas Riener (55 years): Bart Simpson (18 years): Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 14
14 I Classes and Objects: Generating Objects this-reference: Demonstration example - class Car public class Car { private int hp; private String color; // horsepower // paint void anymethod (Car c) { if (this == c) System.out.println("true"); else System.out.println("false"); public static void main (String[] args) { Car audi = new Car(); audi.hp=250; audi.color="red"; Car bmw = new Car(); bmw.hp=400; bmw.color="black ; audi.anymethod(audi); // true audi.anymethod(bmw); // false bmw.anymethod(audi); // false bmw=audi; bmw.anymethod(audi); // true Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 15
15 Classes and Objects: Generating Objects Copy constructor Create a new object based on an already existing object, i.e., with its characteristics/values Approach: (1) create a new (blank) object; (2) copy all instance variables Example public class Person { private String name; private int age; //... // copy constructor Why this() and not Person()? "The method Person() is undefined for the type Person" public Person (Person p) { this(); // reference to any matching constructor in this class // has to be the first statement in a constructor if (p!= null) { // copy all values from object 'p' to the new object this.name = p.name; // also allowed: name = p.name (unambiguous assignment) this.age = p.age; // age = p.age Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 16
16 Classes and Objects: Generating Objects Copy constructor II Dependent on the already existing other constructors, it might be possible to implement the copy constructor by calling an existing constructor Example public class Person { private String name; private int age; public Person (String name, int age) { this.name = name; this.age = age; // copy constructor public Person (Person p) { this(p.name, p.age); // first statement in the constructor Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 17
17 I Classes and Objects: Generating Objects Constructor overloading: Remember unique signature Example int addition (int a, int b){ return a + b; float addition (float a, float b){ return a + b; The call value = addition (4,6); executes the first method The call value = addition (4f,6f); executes the second method Restriction: Single return value, e.g., int x = Input.readInt(); // Integer read function boolean y = Input.readBoolean(); // Boolean read function String z = Input.readLine(); // String read function This would be invalid: int x = Input.readNumber(); float y = Input.readNumber(); String z = Input.readNumber(); Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 18
18 I Classes and Objects: Generating Objects Constructor concatenation Constructors in Java can be concatenated (chained up), i.e., a constructor can call another constructor of that class. The called constructor is interpreted as normal method call; the reference to the constructor is established using this() Differentiation (compiler) to the this-pointer used above: Parentheses Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 19
19 I Classes and Objects: Generating Objects Constructor concatenation: Example public class Car { private String color; // paint private int hp; // horsepower private int regdate; // first registration public class Car { private String color; private int hp; private int regdate; public Car(String color, int hp) { this.color = color; if (hp<0) hp = 0; this.hp = hp; public Car(String color, int hp, int regdate){ this.color = color; if (hp<0) hp = 0; this.hp = hp; this.regdate = regdate; public Car(String color, int hp) { this.color = color; if (hp<0) hp = 0; this.hp = hp; public Car(String color, int hp, int regdate){ this (color, hp); this.regdate = regdate; Avoid duplicate code! Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 20
20 Classes and Objects: Generating Objects Reasons for declaration of (several) special constructors Simple use in programs to define the initial state of objects Most often it makes no sense to generate objects without assignment of initial values, e.g., each person has a name, maybe also an age no default constructor for the person class, i.e., Person(); but one or more special constructors such as Person (String name); Person (String name, int age); Person (String name, String phone, int age); Person (Person p); Generation of objects is not for free... (re)assignments at a later time are also costly therefore: try to assign everything (already known) at time of creation Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 21
21 Classes and Objects: Generating Objects Constructor used to modify (static) class variables For example, static variable 'nrpersons' is used to count the actually allocated person objects public class Person { private static int nrpersons = 0; // number of allocated person objects private String name; private int age; // fields/attributes of a person object public Person() {... // initialize person object nrpersons++; // increase number of person objects public static int getnrpersons () { // class method; 'getter' return nrpersons; Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 22
22 Classes and Objects: Generating and Releasing Objects Constructor is used to modify (static) class variables Create a few person objects... Person welma = new Person(); Person michael = new Person(); Person andreas = new Person(); nrpersons = Some objects are no longer needed; destroyed (garbage collector) michael = null; welma = null; // 'andreas' still exist nrpersons = 3 3 3? Class variable 'nrpersons' (number of allocated objects) is correctly increased (in the constructor), but will not be decreased... is there a concept similar to constructors (object creation) for destroying objects, i.e., that allows to execute concluding instructions? Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 23
23 Classes and Objects: Generating and Releasing Objects One step back... In Java, objects are dynamically allocated by using the new-operator How are objects destroyed (and their memory released for later reallocation) if they are no longer required? In some languages, such as C++, dynamically allocated objects must be manually released by use of a special delete -operator (malloc free) In Java: De-allocation of objects is handled automatically garbage collector Still, you might specify a destructor method to link the release of an object with additional statements or actions...but there is no explicit need to destroy objects as in C++ Some words about the operation principle of the garbage collector When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed Garbage collection only occurs sporadically (if at all) during the execution of your program; it will not occur simply because one or more objects exist that are no longer used... Furthermore, different Java run-time implementations will take varying approaches to garbage collection, but for the most part, you should not have to think about it while writing your programs Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 24
24 Classes and Objects: Releasing Objects Destructors in Java: The 'finalize' method 'finalize()' is working similar to the constructor concept Destructors are used to link the release of an object with additional actions and they get called by the garbage collector (not by the user program) immediately before an object is destroyed Definition: like a ordinary method, named always 'finalize', without parameters, return type 'void' Example The specifier 'protected' prevents access to finalize()by code defined outside its class // called when the object is released protected void finalize() { nrpersons--; // decrease number of allocated person objects 'object = null;' object gets collected when GC runs the next time 'finalize()' is only called during garbage collection and it is not called when an object goes, e.g., out-of-scope a program should provide other means of releasing system resources used by the object it must not rely on finalize() for normal program operation Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 25
25 I Classes and Objects: Generating and Releasing Objects Some important points about finalizers If an object has a finalizer, the finalizer method is invoked sometime after the object becomes unused (or unreachable), but before the garbage collector reclaims the object Java makes no guarantees about when garbage collection will occur or in what order objects will be collected. Java can make no guarantees about when (or even whether) a finalizer will be invoked, in what order finalizers will be invoked, or what thread will execute finalizers The Java interpreter can exit without garbage collecting all outstanding objects, so some finalizers may never be invoked. In this case, though, any outstanding resources are usually freed by the operating system the method addshutdownhook() can safely execute arbitrary code before the Java interpreter exits After a finalizer is invoked, objects are not freed right away. This is because a finalizer method can resurrect an object by storing the thisreference somewhere so that the object once again has references In practice, it is relatively rare to use (or require) a finalize()-method Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 26
26 I SPECIAL KNOWLEDGE Classes and Objects: Generating and Releasing Objects Object cloning: The clone()-method The class Object (super class of every class) specifies a method to create and return a copy of the object the method is called on: protected Object clone() The precise meaning of copy may depend on the class of the object the general intent is that, for any object x, the following expressions will be true (but this is not an absolute requirement) 1) cloned object different from original object x.clone()!= x 2) but both objects are from same class x.clone().getclass() == x.getclass() 3) both objects are similar x.clone().equals(x) == true // no, two different objects! Using clone() requires to call super.clone() and to implement the interface Cloneable (for more information see Java API on class Object) Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 27
27 I SPECIAL KNOWLEDGE Classes and Objects: Generating and Releasing Objects Example: class person with cloneable person objects public class PersonClone implements Cloneable { // fields/attributes of a person object private String name; private int age; public PersonClone () { name = ""; age = 0; // overwritten default public PersonClone clone() { try { return (PersonClone) super.clone(); catch ( CloneNotSupportedException e ) { throw new InternalError(); // this should never happen... public static void main (String arguments[]) { PersonClone p1 = new PersonClone(); p1.name = "andreas"; p1.age = 32; PersonClone p2 = p1.clone(); System.out.println(p2.name + " is " + p2.age); p2.name = "susi"; System.out.println(p1.name + " is " + p1.age); System.out.println(p2.name + " is " + p2.age); Software Development I // Exercises // 08 Objects II (Generating and Releasing Objects) // 28 Independent objects p1, p2 no side effect andreas is 32 andreas is 32 susi is 32
28 Exercises Software Development I 08 Objects II Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute for Pervasive Computing Johannes Kepler University Linz riener@pervasive.jku.at
Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014
Exercises Software Development I 05 Conversions and Promotions; Lifetime, Scope, Shadowing November 5th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute
More information3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.
3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.
More informationProgramming 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 informationIntroduction 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 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 informationClass, 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 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 informationLesson 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 informationCMSC 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 informationCMSC 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 informationC10: Garbage Collection and Constructors
CISC 3120 C10: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/5/2018 CUNY Brooklyn College 1 Outline Recap OOP in Java: composition &
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 informationC11: Garbage Collection and Constructors
CISC 3120 C11: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/5/2017 CUNY Brooklyn College 1 Outline Recap Project progress and lessons
More informationJava Primer 1: Types, Classes and Operators
Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,
More informationChapter 6 Classes and Objects
Chapter 6 Classes and Objects Hello! Today we will focus on creating classes and objects. Now that our practice problems will tend to generate multiple files, I strongly suggest you create a folder for
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationTecniche 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 informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
More information2. Introducing Classes
1 2. Introducing Classes Class is a basis of OOP languages. It is a logical construct which defines shape and nature of an object. Entire Java is built upon classes. 2.1 Class Fundamentals Class can be
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 informationWritten by John Bell for CS 342, Spring 2018
Advanced OO Concepts Written by John Bell for CS 342, Spring 2018 Based on chapter 3 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from other sources. Constructors Constructors
More informationClasses, interfaces, & documentation. Review of basic building blocks
Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform
More informationExercises Software Development I. 06 Arrays. Declaration, Initialization, Usage // Multi-dimensional Arrays. November 14, 2012
Exercises Software Development I 06 Arrays Declaration, Initialization, Usage // Multi-dimensional Arrays November 4, 202 Software Development I Winter term 202/203 Institute for Pervasive Computing Johannes
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 informationGarbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }
Objec,ves Inheritance Ø Overriding methods Garbage collec,on Parameter passing in Java Sept 21, 2016 Sprenkle - CSCI209 1 Assignment 2 Review private int onevar; public Assign2(int par) { onevar = par;
More informationVector and Free Store (Pointers and Memory Allocation)
DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides
More informationPIC 20A The Basics of Java
PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and
More informationObject Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming
Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in
More informationCONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.
Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs
More informationThe issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management
Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored
More information3.1 Class Declaration
Chapter 3 Classes and Objects OBJECTIVES To be able to declare classes To understand object references To understand the mechanism of parameter passing To be able to use static member and instance member
More informationStatic, Final & Memory Management
Static, Final & Memory Management The static keyword What if you want to have only one piece of storage regardless of how many objects are created or even no objects are created? What if you need a method
More informationArgument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.
Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar
More 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 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 informationProgramming 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 informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationObjects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes
Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level
More informationData 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 informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
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 informationJava. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)
Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More informationThe 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 informationEXERCISES SOFTWARE DEVELOPMENT I. 04 Arrays & Methods 2018W
EXERCISES SOFTWARE DEVELOPMENT I 04 Arrays & Methods 2018W Solution First Test DATA TYPES, BRANCHING AND LOOPS Complete the following program, which calculates the price for a car rental. First, the program
More informationDesign Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8
Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns
More informationPOLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE
Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public
More informationPOLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors
POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationComp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has
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 informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationMotivation was to facilitate development of systems software, especially OS development.
A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.
More informationChapter 17 vector and Free Store. Bjarne Stroustrup
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More informationChapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.
Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationFundamental Concepts and Definitions
Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 - Spring 2013 1 Memory Attributes! Memory to store data in programming languages has the following lifecycle
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 informationMotivation was to facilitate development of systems software, especially OS development.
A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationCPS 506 Comparative Programming Languages. Programming Language
CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support
More informationCSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:
CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Thursday 12:00 PM 2:00 PM Friday 8:30 AM 10:30 AM OR request appointment via e-mail
More informationSTRUCTURING OF PROGRAM
Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the
More informationAssumptions. History
Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand
More informationB2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA
B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED 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 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 informationAppendix: Common Errors
Appendix: Common Errors Appendix 439 This appendix offers a brief overview of common errors that occur in Processing, what those errors mean and why they occur. The language of error messages can often
More informationLecture 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 informationQUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?
QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using
More informationLecture 2: Java & Javadoc
Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block
More informationJava Magistère BFA
Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt
More informationLecture 06: Classes and Objects
Accelerating Information Technology Innovation http://aiti.mit.edu Lecture 06: Classes and Objects AITI Nigeria Summer 2012 University of Lagos. What do we know so far? Primitives: int, float, double,
More informationExercises Software Development I. 03 Data Representation. Data types, range of values, internal format, literals. October 22nd, 2014
Exercises Software Development I 03 Data Representation Data types, range of values, ernal format, literals October 22nd, 2014 Software Development I Wer term 2013/2014 Priv.-Doz. Dipl.-Ing. Dr. Andreas
More informationOverview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017
Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable
More informationObject Oriented Programming. What is this Object? Using the Object s Slots
1 Object Oriented Programming Chapter 2 introduces Object Oriented Programming. OOP is a relatively new approach to programming which supports the creation of new data types and operations to manipulate
More informationIntroduction to Java
Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn
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 informationSelected Questions from by Nageshwara Rao
Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Questionnaire Results - Java Overview - Java Examples
More informationCOE318 Lecture Notes Week 4 (Sept 26, 2011)
COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationAIMS Embedded Systems Programming MT 2017
AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors
More informationOOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.
OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.
More informationObject-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007
Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you
More informationM301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism
Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC 330 Spring 2017 1 Memory Attributes Memory to store data in programming languages has the following lifecycle
More informationGoal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search
Goal Generic Programming and Inner classes First version of linear search Input was array of int More generic version of linear search Input was array of Comparable Can we write a still more generic version
More informationObject Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes
1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist
More informationCMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am
CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103
More informationIn this lab we will practice creating, throwing and handling exceptions.
Lab 5 Exceptions Exceptions indicate that a program has encountered an unforeseen problem. While some problems place programmers at fault (for example, using an index that is outside the boundaries of
More informationHandout 7. Defining Classes part 1. Instance variables and instance methods.
Handout 7 CS180 Programming Fundamentals Spring 15 Page 1 of 8 Handout 7 Defining Classes part 1. Instance variables and instance methods. In Object Oriented programming, applications are comprised from
More informationSchool of Informatics, University of Edinburgh
CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions
More informationCMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection
CMSC 330: Organization of Programming Languages Memory Management and Garbage Collection CMSC330 Fall 2018 1 Memory Attributes Memory to store data in programming languages has the following lifecycle
More information