AP CS Unit 6: Inheritance Programs

Similar documents
3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

APCS Semester #1 Final Exam Practice Problems

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP CS Unit 8: Inheritance Exercises

AP CS Unit 6: Inheritance Exercises

AP CS Unit 6: Inheritance Notes

Java Classes, Inheritance, and Interfaces

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

AP CS Unit 3: Control Structures Notes

CS1150 Principles of Computer Science Objects and Classes

CS Week 13. Jim Williams, PhD

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Practice Midterm 1. Problem Points Score TOTAL 50

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

CS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016

CSCE145 Test 2-Review 03/29/2015 Hongkai Yu

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

I. True/False: (2 points each)

Unit 4: Classes and Objects Notes

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CH. 2 OBJECT-ORIENTED PROGRAMMING

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ June Exam

CS 102/107 - Introduction to Programming Midterm Exam #2 - Prof. Reed Spring 2011

Lesson11-Inheritance-Abstract-Classes. The GeometricObject case

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

CS1083 Week 2: Arrays, ArrayList

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

The class Object. Lecture CS1122 Summer 2008

Inheritance and Polymorphism

JAVA MOCK TEST JAVA MOCK TEST II

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Programming Exercise 14: Inheritance and Polymorphism

Introduction to Computer Science Unit 2. Notes

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Rules and syntax for inheritance. The boring stuff

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

Use the scantron sheet to enter the answer to questions (pages 1-6)

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

AP CS Unit 7: Interfaces. Programs

AP Computer Science Unit 1. Programs

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2010

Lecture 5: Methods CS2301

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Lecture 13: Two- Dimensional Arrays

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Making New instances of Classes

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Class, Variable, Constructor, Object, Method Questions

Instance Method Development Demo

Introduction to Computer Science Unit 2. Notes

AP CS Unit 7: Arrays Exercises

CS 302 Week 9. Jim Williams

More Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.

Exam 1 - (20 points)

AP CS Unit 4: Classes and Objects Programs

Programming overview

ITI Introduction to Computing II

CSE 214 Computer Science II Java Classes and Information Hiding

Midterm Examination (MTA)

INHERITANCE. Spring 2019

Chapter 15: Object Oriented Programming

Introduction to Inheritance

CONDITIONAL EXECUTION

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CS 101 Spring 2007 Midterm 2 Name: ID:

Java Magistère BFA

Extending Classes (contd.) (Chapter 15) Questions:

Inheritance: Definition

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012

CS 101 Fall 2006 Midterm 3 Name: ID:

Practice for Chapter 11

25. Generic Programming

Lecture 2: Java & Javadoc

Creating Java Programs with Greenfoot

ITI Introduction to Computing II

CS170 Introduction to Computer Science Midterm 2

Computer Science II (20073) Week 1: Review and Inheritance

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Chair of Software Engineering Java and C# in Depth

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming Languages and Techniques (CIS120)

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

Inheritance (Part 5) Odds and ends

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

Quarter 1 Practice Exam

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Transcription:

AP CS Unit 6: Inheritance Programs Program 1. Complete the Rectangle class. The Rectangle public class Rectangle{ class represents private int x1, y1, x2, y2; a rectangle in a standard coordinate plane with the sides of the rectangle being parallel to the x and y axes. (x1, y1) represent the lower left hand corner of the rectangle. (x2, y2) represent the upper right hand corner of the rectangle. Test your code with the code to the right. public Rectangle( int x1, int y1, int x2, int y2){ if ( x1 >= x2 y1 >= y2 ) throw new IllegalArgumentException("x1 >= x2 or y1 >= y2"); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; public int getperimeter(){ returns the perimeter of the rectangle. ----à Use the distance method that the Point class inherits public int getarea(){ from Point2D class. returns the area of the rectangle public class RunRectangle{ Rectangle r1 = new Rectangle( -1, 4, 2, 8 ); System.out.println( r1.getperimeter() ); // 14 System.out.println( r1.getarea() ); // 12 Rectangle r2 = new Rectangle( 2, 5, 2, 6 ); //java.lang.illegalargumentexception: x1 >= x2 or y1 >= y2 Now write the Square class that extends the Rectangle class. The Square class has no instance variables. Its constructor has three parameters: the x and y coordinates of the lower left hand corner and the length of a side. When finished the Square class should be no more than 5 line long. Use the code to the right to test it. crash public class RunSquare{ Square s = new Square( 5, 6, 9 ); System.out.println( s.getarea() ); // 81 System.out.println( s.getperimeter() ); // 36

Program 2. Complete the Course and Weighted classes. public class Course{ The Weighted class is a subclass of Course and private String name; it represents a course with a weighted grade private double grade; (e.g. an AP or honors course) public Course( String s ){ name = s; grade = 0; public void setgrade( double g ){ grade = g; public double getgrade(){ return grade; The Weighted class should have the following: - one instance variable, a double, which is the weight for a particular course. (The course name and unweighted grade are part of the super class.) The constructor header is this: public Weighted( double w, String s ) where w is the weight and s is the name A method that returns the weighted grade: public double getweightedgrade() // see note below public String tostring(){ return name + ": " + grade; And override the tostring method. See the sample code below to determine what these should do. Do NOT add any extra instance variables or methods. Here s some a quote from the Oracle documentations, When overriding a method, you might want to use the annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error. This is a good idea because sometimes people accidently misspell the method name and end up writing a new method instead of overriding an existing method. It is optional. - https://docs.oracle.com/javase/tutorial/java/iandi/override.html Use this class to test your Weighted class. Notice that the subclass cannot directly access the private instance variables of Course but can call its public methods. public class RunCourse1{ Course c = new Course( "Intro to Java" ); c.setgrade( 92 ); System.out.println( c.getgrade() ); // 92.0 System.out.println( c ); // Intro to Java: 92.0 Weighted w = new Weighted( 1.2, "APCS" ); w.setgrade( 88 ); System.out.println( w.getgrade() ); // 88.0 System.out.println( w.getweightedgrade() ); // 105.6 System.out.println( w ); // APCS: 88.0, weighted: 105.6

Program 3. Using the Course and Weighted classes from problem 2, complete the following program. public class RunManyCourses{ String [] names1 = {"Honors English", "APCS", "Chemistry", "History" ; double [] grades1 = { 71, 85, 94, 87 ; Double [] weights1 = { 1.1, 1.2, null, null ; Course [] c = setup( names1, grades1, weights1 ); for ( Course cor : c ) System.out.println( cor ); double avg = getunweightedaverage( c ); System.out.println ( "Unweighted average: " + avg ); double wavg = getweightedaverage( c ); System.out.println ( "Weighted average: " + wavg ); System.out.println ( "\n************************\n" ); String [] names2 = {"Reading", "Math", "AP US History" ; double [] grades2 = { 90, 80, 85 ; Double [] weights2 = { null, null, 1.2 ; c = setup( names2, grades2, weights2 ); for ( Course cor : c ) System.out.println( cor ); Your output should look like this: Honors English: 71.0, weighted: 78.10000000000001 APCS: 85.0, weighted: 102.0 Chemistry: 94.0 History: 87.0 Unweighted average: 84.25 Weighted average: 90.275 ************************ Reading: 90.0 Math: 80.0 AP US History: 85.0, weighted: 102.0 Unweighted average: 85.0 Weighted average: 90.66666666666667 avg = getunweightedaverage( c ); System.out.println ( "Unweighted average: " + avg ); wavg = getweightedaverage( c ); System.out.println ( "Weighted average: " + wavg ); public static Course [] setup( String [] s, double [] g, Double [] wts ){ Returns an array filled with Course and Weighted objects. Use the String elements for the names. If a particular weight is null then create a Course object; otherwise create a Weighted object. Use the g array to set the grades. public static double getunweightedaverage( Course[] c ){ Returns the unweighted average of all the courses. public static double getweightedaverage( Course[] c ){ Returns the weighted average of all the courses. If a course is not weighted then use its regular, unweighted grade.

Program 4. Copy the Ring class and write the MagicRing class. public class Ring{ The MagicRing class is a subclass of the Ring private int value; class. public Ring( int v ){ value = v; public int getvalue(){ return value; public String tostring(){ return "ring worth $" + value; It has one instance variable, a Boolean. If true then this is a lucky magic ring; otherwise it is an unlucky magic ring. Write a constructor that has one parameter, an int the represents the value of the ring. Randomly assign the instance variable a value so that there s a 50% chance of it being true or false. Write an accessor method for the instance variable. Override the tostring method so that it is consistent with the outputs shown in the sample code below. Complete the code below. To the right is some sample output. public class RunRings{ Ring [] rings = new Ring[10]; for ( int n=0; n<10; n++ ){ rings[n] = get(); System.out.println( rings[n] ); lucky ring worth $6 ring worth $15 lucky ring worth $15 lucky ring worth $15 ring worth $16 unlucky ring worth $11 ring worth $14 ring worth $15 unlucky ring worth $12 lucky ring worth $7 int totalvalue = gettotalvalue( rings ); Total value: 126 System.out.println( "\ntotal value: " + totalvalue ); There are 4 lucky magic rings int count = countluckymagicrings( rings ); System.out.println( "There are " + count + " lucky magic rings" ); public static Ring get(){ 50% of the time this returns a ring and 50% of the time it returns a magic ring. The value of any ring is a random number between 5 and 20 public static int gettotalvalue( Ring [] r ){ Returns the sum of all the values of all the rings public static int countluckymagicrings( Ring [] r ){ Returns the number of lucky magic rings in the array

Program 5. This project contains 5 classes though most are short. When you run the finished program, it should display a 4 by 4 grid that looks something like this: 6 9 6 9 4 3 B 2 6 1 Joe 4 4 B!! 1 9 The player is next to 20 bars of gold. The player is next to 2 bombs. 1 of them is/are deadly. The grid contains: 1 player named Joe (Keep the name short.) 2 bombs (B!! if deadly, B if not deadly) 13 locations that contain gold bars (the numbers indicate the number of bars at each location. The player, bombs, and gold are all assigned random locations in the grid. public abstract class Piece { private int row, col; public class Gold extends Piece { private int bars; public Piece( ) { row = -1; col = -1; public void setlocation( int r, int c ){ row = r; col = c; public boolean nextto( Piece p ){ returns true if p is adjacent to this piece (locations at a diagonal count) public Gold() { bars = (int)(9 * Math.random() )+ 1; public int get() { return bars; public String tostring() { return "" + bars; public class Player extends Piece { private String name; public Player( String s ) { name = s; public class Bomb extends Piece{ private boolean deadly; public Bomb() { 50% of the time deadly should be true public String tostring() { return name; public boolean isdeadly() { return deadly; public String tostring() { if deadly is true, return "B!!" else return B

Now here s the class that puts it all together and where you have to do some thinkin. public class Runner { public static void main(string[] args) { Piece [][] grid = new Piece[4][4]; place( grid, new Player( "Joe" ) ); // use the place method to put two bombs in the grid (two lines of code) // put 13 Gold objects in the remaining locations in the grid (one loop) // print out grid (nested loops) Player p = findplayer( grid ); int num = getgold( grid, p ); System.out.println("The player is next to " + num + " bars of gold." ); Bomb[] bombs = findbombs( grid, 2 ); int nexttobombs = 0; int nexttodeadly = 0; // count the bombs (deadly or not) near the player // you ll need a loop and the nexttobombs and nexttodeadly variables System.out.println("The player is next to " + nexttobombs + " bombs." ); if ( nexttobombs>0 ) System.out.println( nexttodeadly + " of them is/are deadly.\n" ); public static void place( Piece [][] aa, Piece p ){ // generate a random row and column while ( aa[row][col]!= null ){ // generate another random row and column aa[row][col] = p; p.setlocation( row, col ); public static Player findplayer( Piece [][] aa ){ // searches the array for the first piece that is an instance of the Player class // return this value // return null if a Player is not found (though you will find one) public static int getgold( Piece [][] aa, Player p ){ // Given a player, return the number of adjacent bars of gold. public static Bomb[] findbombs( Piece [][] aa, int num ){ // Returns an array of Bombs that are in aa, num is the number of bombs