Solutions to Quick Check Questions. Defining Your Own Classes Part 1



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

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

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

Java Classes. GEEN163 Introduction to Computer Programming

LAB4 Making Classes and Objects

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

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Java CPD (I) Frans Coenen Department of Computer Science

Introduction to Object-Oriented Programming

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Chapter 13 Storage classes

Object-Oriented Programming Lecture 2: Classes and Objects

Basic Object-Oriented Programming in Java

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

JAVA - INNER CLASSES

Building Java Programs

Doors User Data File Export/Import

Inheritance, overloading and overriding

CSE 1020 Introduction to Computer Science I A sample nal exam

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Item 7: Prefer Immutable Atomic Value Types

CISC 181 Project 3 Designing Classes for Bank Accounts

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

Object Oriented Software Design II

Programming Methods & Java Examples

New Tricks for an Old Tool: Using Custom Formats for Data Validation and Program Efficiency

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

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

C++ Programming Language

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

CSE 308. Coding Conventions. Reference

Introduction to Java. CS 3: Computer Programming in Java

Tutorial on C Language Programming

Sample CSE8A midterm Multiple Choice (circle one)

OpenCL Static C++ Kernel Language Extension

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Training Needs Analysis

An Incomplete C++ Primer. University of Wyoming MA 5310

Object Oriented Software Design II

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

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

C++ INTERVIEW QUESTIONS

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

C Compiler Targeting the Java Virtual Machine

CSc 372. Comparative Programming Languages. 21 : Haskell Accumulative Recursion. Department of Computer Science University of Arizona

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

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

Merchant Card Processing Procedures

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

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

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

Basics of Java Programming Input and the Scanner class

Java from a C perspective. Plan

Sources: On the Web: Slides will be available on:

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

CSE 2221 Midterm Exam #1 SAMPLE

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

Computer Programming C++ Classes and Objects 15 th Lecture

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

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

Fundamentals of Programming and Software Development Lesson Objectives

Result Entry by Spreadsheet User Guide

MERCHANT SERVICES ONLINE. TD Retail Card Services

EXTREME: EXecuTable Requirements Engineering, Management and Evolution. Dr. Ella Roubtsova Open University of the Netherlands

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

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

Moving from CS 61A Scheme to CS 61B Java

Oracle Tuxedo Systems and Application Monitor (TSAM)

AP Computer Science Java Subset

/* File: blkcopy.c. size_t n

CIS 544 Advanced Software Design and Development. Project Management System. Oreoluwa Alebiosu

CMSC 202H. ArrayList, Multidimensional Arrays

Realizing Enterprise Integration Patterns in WebSphere

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:

Introduction to Programming

Description of Class Mutation Mutation Operators for Java

CS193j, Stanford Handout #10 OOP 3

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

13 Classes & Objects with Constructors/Destructors

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) {

Software Engineering Techniques

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

A deeper look at Inline functions

CS170 Lab 11 Abstract Data Types & Objects

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Chapter 5 Functions. Introducing Functions

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

Transcription:

Solutions to Quick Check Questions 4 Defining Your Own Classes Part 1 4.1 First Example: Defining and Using a Class 1. Extend the Bicycle class by adding the second data member tagno of type String. Declare this data member as private. class Bicycle { // Data Members private String ownername; private String tagno; //Constructor: Initialzes the data member public void Bicycle( ) { ownername = "Unknown"; tagno = "Unassigned"; 2. Add a new method to the Bicycle class that assigns a tag number. This method will be called as Bicycle bike; bike = new Bicycle( ); 1

2 Solutions to Chapter 4 Quick Check Questions Answer class Bicycle { bike.settagno("2004-134r"); public void settabno(string number) { tagno = number; 3. Add a another method to the Bicycle class that returns the bicycle s tag number. This method will be called a Answer class Bicycle { Bicycle bike; bike = new Bicycle( ); String tag = bike.gettagno( ); public String gettagno( ) { return tagno; 4.2 Second Example: Defining and Using Multiple Classes 1. What is the output from the following code fragement? Account acct; acct = new Account( ); acct.setinitialbalance(250); acct.add(20);

Solutions to Chapter 4 Quick Check Questions 3 System.out.println("Balance: " + acct.getcurrentbalance()); Answer: Balance: 270 2. Write a code fragment to declare and create two Account objects named acc1 and acct2. Initialize the balance to $300 and $500, respectively. Set the name of owner for both accounts to John Doe. Answer: Account acct1, acct2; acct1 = new Account( ); acct2 = new Account( ); acct1.setinitialbalance(300); acct2.setinitialbalance(300); 4.3 Matching Arguments and Parameters No Quick Check Questions. 4.4 Passing Objects to a Method No Quick Check Questions. 4.5 Constructors 1. Which of the following constructors are invalid? public int ClassA(int one) { <--- Invalid

4 Solutions to Chapter 4 Quick Check Questions public ClassB(int one, int two) { <--- Valid void ClassC( ) { <--- Invalid 1. Invalid. The constructor does not have a return type. 2. Valid. 3. Invalid. The void modifier is not valid with the constructor 2. What is the main purpose of a constructor? The main purpose of a constructor is to initialize the data members of a class fully so an instance will be created in a valid state. 3. Complete the following constructor : class Test { private double score; public Test(double val) { //assign the value of parameter to //the data member Answer class Test { private double score; public Test(double val) { score = val;

Solutions to Chapter 4 Quick Check Questions 5 4.6 Information Hiding and Visibility 1. If the data member speed is private, is the following statement valid in a client program? Robot aibo; aibo = new Robot(); double currentspeed = aibo.speed; <--- Invalid No, the statement is invalid. You do not have a direct access to the private data members of a class from a client code. 2. Suppose you wrote down important information such as your bank account number, student registration ID, and so forth, on a single sheet of paper. Will this sheet be declared private, and kept in your desk drawer, or public, and placed next to the dorm s public telephone? Confidential information should be hidden from the public view or access, so the sheet should be declared private and hidden from the public. 3. Identify the private methods from the following diagram: MyClass mydata : double + MyClass( ) + methodone(double) : void - methodtwo(double) : double - methodthree(double) : double Private methods are methodtwo and methodthree.

6 Solutions to Chapter 4 Quick Check Questions 4.7 Class Constants 1. Declare two class constants named MIN_BALANCE and MAX_BALANCE whose data types are double. public static final double MIN_BALANCE = 100.0; public static final double MAX_BALANCE = 500.0; 2. Is there any problem with the following declarations? class Question { private final int MAX = 20; The static modifier is missing in the declaration. 3. Modify the Dice class so its instances will generate a number between 5 and 15, inclusively. class Dice { //Data Members private static final int MAX_NUMBER = 15; private static final int MIN_NUMBER = 5; //the rest is the same 4.8 Local Variables 1. How is a local variable different from an instance variable? Local variables are temporary variables used only by the method in which they are declared. Memory space for local variables exist only during the execution of the method. 2. Rewrite the following method using local variables:

Solutions to Chapter 4 Quick Check Questions 7 public int totalcharge(int amt) { return (balance -(int) Math.round(amt * 1.5)); Answer public int totalcharge(int amt) { int result = balance -(int) Math.round(amt * 1.5); return result; 4.9 Calling Methods of the Same Class 1. Suppose a class Alpha includes a method called compute that accepts no arguments. Define another method of Alpha named mymethod that calls the compute method. class Alpha { public void mymethod( ) { compute( ); 2. Why should duplication of code be avoided? Duplication of code should be avoided as much as possible to streamline the modification process and make the process less error-prone. 4.10 Changing Any Class to a Main Class No Quick Check Questions

8 Solutions to Chapter 4 Quick Check Questions 4.11 Sample Development: Loan Calculator No Quick Check Questions