Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:



Similar documents
J a v a Quiz (Unit 3, Test 0 Practice)

Part I. Multiple Choice Questions (2 points each):

Basic Object-Oriented Programming in Java

Java Interview Questions and Answers

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Object-Oriented Programming Lecture 2: Classes and Objects

Chapter 2: Elements of Java

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Contents. 9-1 Copyright (c) N. Afshartous

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Stack vs. Heap. Introduction to Programming. How the Stack Works. Primitive vs. Reference Types. Stack

Example of a Java program

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Moving from CS 61A Scheme to CS 61B Java

C++ INTERVIEW QUESTIONS

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Java Basics: Data Types, Variables, and Loops

Lecture 5: Java Fundamentals III

This explanations are for absolute beginners. Skilled programmers should (and probably will) use more effective approach.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object Oriented Software Design

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java. CS 3: Computer Programming in Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

public static void main(string[] args) { System.out.println("hello, world"); } }

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Sample CSE8A midterm Multiple Choice (circle one)

Introduction to Java

More on Objects and Classes

CSC 221: Computer Programming I. Fall 2006

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

13 Classes & Objects with Constructors/Destructors

Object-Oriented Programming in Java

AP Computer Science Java Subset

Java CPD (I) Frans Coenen Department of Computer Science

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Chapter 2 Elementary Programming

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Pemrograman Dasar. Basic Elements Of Java

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

The C Programming Language course syllabus associate level

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Introduction to Object-Oriented Programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Moving from C++ to VBA

JAVA ARRAY EXAMPLE PDF

Conversion Constructors

Programming Fundamentals I CS 110, Central Washington University. November 2015

Object Oriented Software Design

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Chapter 1 Java Program Design and Development

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Building Java Programs

CS170 Lab 11 Abstract Data Types & Objects

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CMSC 202H. ArrayList, Multidimensional Arrays

WRITING DATA TO A BINARY FILE

Stacks. Linear data structures

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Introduction to Java Lecture Notes. Ryan Dougherty

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

CS 106 Introduction to Computer Science I

Chapter 2 Introduction to Java programming

Abstract Class & Java Interface

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

CISC 181 Project 3 Designing Classes for Bank Accounts

Statements and Control Flow

Inheritance, overloading and overriding

Explain the relationship between a class and an object. Which is general and which is specific?

STATIC VARIABLE/ METHODS, INHERITANCE, INTERFACE AND COMMAND LINE ARGUMENTS

(Eng. Hayam Reda Seireg) Sheet Java

Compile-time type versus run-time type. Consider the parameter to this function:

Crash Course in Java

Building Java Programs

Programmierpraktikum

Continuous Integration Part 2

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

To Evaluate an Algebraic Expression

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Transcription:

In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our class. In fact, it is a special type of method called a constructor method. Although we didn't create this method, Java automatically creates a default constructor method. The constructor method has the same identifier as the class (in this case, the word 'Function' is the identifier for both the constructor and the class). Constructor methods are instance methods used to initialize new objects at the time they are created. The default constructor method will perform the following initializations: 1. All numeric fields are set to zero. 2. All boolean fields are set to false. 3. All reference fields (i.e., fields that refer to an object, rather than a primitive data type) are set to null. Note: The value of null is, in essence, 'nowhere'. By setting a reference field to null, we are explicitly stating that it does not refer to any object. On the other than, an uninitialized reference field could theoretically contain any value, including locations in memory occupied by running programs. This is one of the many reasons why it is critical to always initialize all variables to known starting values. Redefining the Constructor Method Java creates a constructor method by default for all classes. It is possible, however, to specify our own constructor method, which will then replace the default constructor. Suppose, in the class, we created the following constructor: public (int n, int d) this.num = n; this.den = d; Notice that this constructor method accepts the integer arguments n and d. We might create a new instance of a object with f = new (2, 3); This would declare f to be of type, create an object of type in memory, set f to refer to that object in memory, and then initialize the object to represent the fraction 2 3. Some notes about our first constructor method: 1. The identifier of the constructor is exactly the same as the identifier of the class. 2. Unlike every method we have seen so far, the constructor method does not specify a return type (not even void). 3. The constructor is an instance method, allowing us to use the keyword this. 4. The call to the constructor requires the use of the keyword new. 5. The parameters were called n and d to avoid any potential conflicts with num and den (since the use of the keyword this is optional). 28. Oct. 2010 Page 1 of 5

Overloading Constructors Like other methods we have previously discussed, it is also possible to overload a constructor method. This allows us to create multiple versions of the constructor method, each with its own signature and each doing some different kind of initialization. // constructor to initialize the new object to be // equal to an existing object f public ( f) this.num = f.num; this.den = f.den; Once we have created our own constructor method, the default constructor method no longer operates. It is possible, however, that we wish to have a constructor method with no parameters, in which case we will have to write our own. In the case of the class, the default constructor method will initialize the numerator and denominator to zero, creating the fraction 0 0. It might be more logical to initialize the fraction to something mathematically safer, such as 0 1. public () this.num = 0; this.den = 1; Consider the results of the following code fragment: p = new (3, 5); q = new (p); r = new (); p q r num 3 den 5 num 3 den 5 num 0 den 1 28. Oct. 2010 Page 2 of 5

Questions & Exercises 1. class. (a) Extend the definition of the class that we have been developing to include the constructors discussed in this section. (b) Write a main method that first constructs two objects representing the fractions 5/7 and 3/8, and then creates two other objects whose values are the sum and product of the original fractions. The method should output the numerator and denominator values for each fraction. We will develop a more refined output of a object in the future. Use the methods plus and times from the lesson on instance methods to help you complete this task. 2. For the class Circle, as previously discussed: (a) Write a constructor method that has no parameters. The method should construct a Circle object with centre (0,0) and radius 1. (b) Write a constructor method that has three parameters representing the coordinates of the centre (x,y) and the radius, r, of the circle to be constructed. (c) Write a constructor with a single parameter of type Circle. The method should construct a new Circle object with the same field values as those of the circle specified by the parameter. 28. Oct. 2010 Page 3 of 5

Solutions 1. (a) // This replaces the default constructor for the class public () this.num = 0; this.den = 1; /** * This is another constructor for the class. * It can be distinguished from other constructors by the * parameter list. */ public (int n, int d) this.num = n; this.den = d; /** * Constructor to initialize the new object to be equal to * an existing object f */ public ( f) this.num = f.num; this.den = f.den; (b) class Test public static void main (String[] args) f1 = new (5, 7); f2 = new (3, 8); f3 = f1.plus(f2); f4 = f1.times(f2); System.out.println(" 1: " + f1.num + "/" + f1.den); System.out.println(" 2: " + f2.num + "/" + f2.den); System.out.println(" 3: " + f3.num + "/" + f3.den); System.out.println(" 4: " + f4.num + "/" + f4.den); 2. (a) public Circle() // initialize instance variables x = 0; y = 0; r = 1; 28. Oct. 2010 Page 4 of 5

(b) public Circle(double x, double y, double r) // initialise instance variables this.x = x; this.y = y; this.r = r; (c) public Circle(Circle copy) this.x = copy.x; this.y = copy.y; this.r = copy.r; 28. Oct. 2010 Page 5 of 5