contain a geometry package, and so on). All Java classes should belong to a package, and you specify that package by typing:

Similar documents
Lab 1: Introduction to Java

Eclipse Setup. Opening Eclipse. Setting Up Eclipse for CS15

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Mobile Computing Professor Pushpedra Singh Indraprasth Institute of Information Technology Delhi Andriod Development Lecture 09

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

Slide 1 CS 170 Java Programming 1 Testing Karel

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

COPYRIGHTED MATERIAL. Starting Strong with Visual C# 2005 Express Edition

MITOCW watch?v=0jljzrnhwoi

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

1) Log on to the computer using your PU net ID and password.

Arduino IDE Friday, 26 October 2018

Linked Lists. What is a Linked List?

Client Side JavaScript and AJAX

Homework 09. Collecting Beepers

CS390 Principles of Concurrency and Parallelism. Lecture Notes for Lecture #5 2/2/2012. Author: Jared Hall

Java Programming Constructs Java Programming 2 Lesson 1

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Using Eclipse and Karel

Gearing Up for Development CS130(0)

Laboratory 1: Eclipse and Karel the Robot

BEGINNER PHP Table of Contents

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

Assignment #1: /Survey and Karel the Robot Karel problems due: 1:30pm on Friday, October 7th

Mehran Sahami Handout #7 CS 106A September 24, 2014

MITOCW watch?v=9h6muyzjms0

Slide 1 CS 170 Java Programming 1

Chris' Makefile Tutorial

Lecture 02, Fall 2018 Friday September 7

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

MITOCW watch?v=kz7jjltq9r4

Slide 1 CS 170 Java Programming 1 Duration: 00:00:49 Advance mode: Auto

Assignment #1: and Karel the Robot Karel problems due: 3:15pm on Friday, October 4th due: 11:59pm on Sunday, October 6th

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Mobile App:IT. Methods & Classes

Math Modeling in Java: An S-I Compartment Model

The following content is provided under a Creative Commons license. Your support

Skill 1: Multiplying Polynomials

Computer and Programming: Lab 1

EE 422C HW 6 Multithreaded Programming

Ruby on Rails Welcome. Using the exercise files

Assignment #4 Minesweeper

Introduction to Game Programming Lesson 4 Lecture Notes

Using the API: Introductory Graphics Java Programming 1 Lesson 8

+ Abstract Data Types

How To Add Songs To Ipod Without Syncing >>>CLICK HERE<<<

Post Experiment Interview Questions


} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Introduction to Computation and Problem Solving

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

printf( Please enter another number: ); scanf( %d, &num2);

1 Getting started with Processing

Lab 1: Setup 12:00 PM, Sep 10, 2017

APPM 2460 Matlab Basics

CS 134 Programming Exercise 2:

CS 051 Homework Laboratory #2

From time to time Google changes the way it does things, and old tutorials may not apply to some new procedures.

Semester 2, 2018: Lab 1

CSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

Implement an ADT while using Subversion

MITOCW watch?v=zm5mw5nkzjg

MITOCW watch?v=flgjisf3l78

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

Instructor (Mehran Sahami):

6.001 Notes: Section 6.1

COMP 105 Homework: Type Systems

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras

What's the Slope of a Line?

Hi everyone. Starting this week I'm going to make a couple tweaks to how section is run. The first thing is that I'm going to go over all the slides

Project 5 - The Meta-Circular Evaluator

CISC 181 Lab 2 (100 pts) Due: March 4 at midnight (This is a two-week lab)

mk-convert Contents 1 Converting to minikanren, quasimatically. 08 July 2014

Part 1: Complete XMLElement

Unit E Step-by-Step: Programming with Python

Tips from the experts: How to waste a lot of time on this assignment

Getting Started. 1 by Conner Irwin

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

CS61A Notes Week 1A: Basics, order of evaluation, special forms, recursion

I'm Andy Glover and this is the Java Technical Series of. the developerworks podcasts. My guest is Brian Jakovich. He is the

05. SINGLETON PATTERN. One of a Kind Objects

Helping the Compiler Help You. Thomas Dy

Summer Assignment for AP Computer Science. Room 302

Stage 11 Array Practice With. Zip Code Encoding

Setting Up Your ios Development Environment. For Mac OS X (Mountain Lion) v1.0. By GoNorthWest. 5 February 2013

The purpose of this tutorial is to introduce you to the Construct 2 program. First, you will be told where the software is located on the computer

Chapter 4 Lab. Loops and Files. Objectives. Introduction

These are notes for the third lecture; if statements and loops.

COMP2100/2500 Lecture 17: Shell Programming II

Reading How the Web Works

Activity Guide APIs and Using Functions with Parameters

Module 6. Campaign Layering

Chapter 1. Getting Started

Project #1 Seamcarve

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

InfoSphere goes Android Flappy Bird

1.00 Lecture 2. What s an IDE?

Transcription:

Introduction to Java Welcome to the second CS15 lab! By now we've gone over objects, modeling, properties, attributes, and how to put all of these things together into Java classes. It's perfectly okay if you are feeling a little overwhelmed at this point; you've gone over a lot of new material very quickly. But don't worry! This lab will help reinforce what you've learned by leading you through writing a small Java program. The TAs walking around are there to help, so if you have any questions about the lab, the lectures, or general course material, please ask us (sorry, this is not a time to ask specific assignment questions). General Programming Guidelines Our goal is to get started using Java and learn how to create a class from scratch. Before we get started on the mini assignment, let's go over some general Java and programming guidelines: Packages Classes Methods and Parameters Constructors Packages Java programs are built upon classes each program needs to have at least one. As the programs you write grow in size, it can get messy to have all of your classes lying everywhere. Thankfully, Java organizes classes into packages. This is an extension of functions and classes to help keep code organized and manageable. The best way to think of a package is as a stand alone group of classes that performs a certain task. For example, if your program was a video game, possible packages within that game could include the graphics package, the physics package, the AI package, the Networking package, etc. Packages can consist of smaller packages (the physics package could contain a math package, the graphics package could 1 contain a geometry package, and so on). All Java classes should belong to a package, and you specify that package by typing: package <some package>; at the very beginning of the file (before you even declare the class), and without the angle brackets. All this being said, the programs in CS15 aren't big enough to need multiple packages, so the name of your packages will simply be the names of the programs. 1 The only real exception is when you are writing a very small Java program that consists of only one class.

Classes Now that we understand packages, let's move onto making a new class. Each Java class 2 should be in its own file, with the name of the class being the name of the file. All Java files should end in.java. For example, a Clown class would be saved as Clown.java. If you don t remember how to declare a class, you can look back over the lecture notes, although Eclipse will generate the class declaration for you. Check Point 1 1. Run the cs015_install labintroscript to get the stencil code for lab 1. This will create an App.javafile in /home/<yourlogin>/course/cs015/labintro/. 2. Open Eclipse and find the labintro package in your cs015 project folder (if you don t see it try hitting F5 to refresh). The labintro package should contain a single class called App.java. 3. With your labintro package selected, go to File >> New >> Class. 1. For the Source folder, make sure you have cs015, if not, use the Browse option to locate the cs015 folder. 2. For Package, make sure you have labintro, if not, use the Browse option to locate the labintro folder. 3. For Nametype: CupcakeMaker(.javawill be automatically appended). 4. Hit Finish. 4. The file should be created and opened in the Editor Region. Eclipse generates the package declaration and the class body. Write an empty constructor for CupcakeMaker.This is just a simple constructor that does nothing. 5. Right click App.javaand hit Run As >> Java Application to run it. Methods and Parameters A class can't do anything without you defining some capabilities for it. If you had a Robotclass, you would want it to do something cool like: walk, dance, cook, maybe even do your CS15 assignments for you. Java models these capabilities using methods. Methods have a specific syntax; refer to lectures or the book if you don't remember. Sometimes a method needs outside information in order to perform its task. A way to pass information to a method is through parameters. For example, a Robot's cook(...)method needs to know what to cook. Since your Robotis a culinary genius, if you didn't use parameters, you would end up writing tons of cook methods for every possible dish your Robot 2 There are classes called inner classes that do not follow this rule. We will be going over them in class in 2 weeks.

can cook! Just think: cookchicken(), cookpork(), cooksteak(), cooktomatoes()...or you can write one method that takes in a food that you want your Robotto cook as a parameter. When a method takes a parameter, it uses that parameter as a variable. Constructors Let's not forget constructors; they are special methods that are automatically called when an object gets instantiated (i.e. every time you call new <someconstructor>();). Every class 3 needs one, and they are usually used to instantiate instance variables and set default values. Going back to our Robotexample, once a new Robothas been built, Java will look in the constructor to see what default values should be given to its color, name, height, weight, etc. Constructors have to be named the same as their class, so a Robotclass will have a Robot constructor. Look into the lecture slides for specific syntax. Just as in any method, parameters are very useful for constructors. They can be used to set up associations (knowledge of other objects) that are not known until an object is instantiated. Remember the DogGroomerand PetShopexample from lecture? We can use a parameter in the Robotclass to let the Robotknow which student it belongs to and what color the student ordered its Robotto be. Now that you're more familiar with the Java syntax, it's time to get down to business... Making a Program For this lab, you're going to be creating your own Cupcake! Currently, the Cupcakedoesn't have frosting, sprinkles, or a cherry. The CupcakeMakerclass that you've started writing will be responsible for creating frosting, sprinkles, and a cherry. It will then add these parts to the empty cupcake. In order to do this, CupcakeMakerwill have to know about the empty cupcake. Since CupcakeMakerdidn't instantiate Cupcake, the best way to do so is through an association using the constructor. 3 If you don't write a constructor, Java will automatically create one for you, but it won't do anything.

Check Point 2 1. Modify the constructor for CupcakeMakerso that it receives one parameter of type cs015.labs.cupcakesupport.cupcake. 2. Inside the constructor of App.java, instantiate an instance of CupcakeMaker passing it the empty Cupcake(look in the code comments to see where this is done). 3. Make sure your parameters are syntactically correct. If you get any errors, Eclipse will show red lines under them. Try to fix the errors. Now it's time to add all the other components. A great place to instantiate the object's components is in the constructor of CupcakeMaker. Let's begin by adding frosting (cs015.labs.cupcakesupport.cupcakefrosting) to the cupcak HOLD UP, ain t no one got time to type out cs015.labs.cupcakesupport.<...>everytime they want to access the provided support code, which brings us to importing classes. When we type cs015.labs.cupcakesupport.cupcakefrosting, we are telling Java that we want to use the CupcakeFrostingclass from the package cs015.labs.cupcakesupport. It would be pretty annoying to have to write out the full package name every time we want to use support code from the package cs015.labs.cupcakesupport(see, it s already annoying!). By importing a class, the Java compiler will automatically fill in the package name of a class, so you can simply refer to cs015.labs.cupcakesupport.cupcakefrostingas CupcakeFrosting. Not only is this a benefit to your quality of life, but it also brings added readability and conciseness to your code. How to Import Classes: In order to import classes, you must tell Java to import specific classes at the top of your code. Here is an example: package SaladMaker; import kitchen.allthingssalad.lettuce; import kitchen.allthingssalad.tomato; import kitchen.allthingssalad.dressing; public class SaladMaker { public SaladMaker(Lettuce l, Tomato t, Dressing d) { <code elided>

} } As you can see, we ve imported classes Lettuce, Tomato, and Dressing from kitchen.allthingssalad. But because we know that we are going to use all of the classes contained in the allthingssaladpackage, so we can import kitchen.allthingssalad.*, which indicates that we re importing all classes contained in the package. This saves us a couple lines of code. Therefore, the following code is synonymous to the above code: package SaladMaker; import kitchen.allthingssalad.*; public class SaladMaker { public SaladMaker(Lettuce l, Tomato t, Dressing d) { <code elided> } } Ok, now we re ready for some frosting. Check Point 3 1. Import all the support code for this lab, which can be found in the package cs015.labs.cupcakesupport. 2. Inside the constructor for CupcakeMaker, instantiate an instance of CupcakeFrosting. Hint: if you re getting an error, make sure you ve completed step 1 correctly. 3. Run the App. You'll see nothing has changed. This is because although you've made the frosting, the empty cupcake has no idea that you've made them. Fortunately, the cupcake has a method you can call to tell it about the frosting you've just made. cs015.labs.cupcakesupport.cupcakehas a method add(...) that takes in a CupcakeFrosting as a parameter and does not return anything. 4. Call the add(...) method inside the CupcakeMaker constructor on the Cupcake object that was passed in and pass it the instance of CupcakeFrostingthat you've just instantiated. 5. Run the App again. Yay! The cupcake has frosting now! If you are having trouble getting the method invocation syntax correct, review the lecture notes. Remember that there are 3 parts to a method invocation: the receiver of the message, the name of the method, and the parameters (if there are any).

Check Point 4 1. Finish up the empty cupcake by adding sprinkles and a cherry in the same way that you added frosting. Here are the classes to add: cs015.labs.cupcakesupport.cupcakesprinkles cs015.labs.cupcakesupport.cupcakecherry Hint: If you successfully imported the support code package, do you have to include th package name? Coding Conventions Programming has a very unique style element to it. While the compiler couldn't care less about what your code looks like, neat and well formatted programs make it much easier to develop, debug, and look back at old code later on. CS15 has a Coding Conventions guideline that you should take a look at. (Coding Style will be part of the rubric for each programming assignment.) Congratulations on finishing lab 1, you are well on your way to becoming an Xtreme Coder! Make sure to get checked off by a TA before leaving!