Chapter 6 – Interacting Objects: Newton’s Lab. topics: objects interacting with each other, using helper classes, using classes from the Java library.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Advertisements

TOPIC 12 CREATING CLASSES PART 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
Games and Simulations O-O Programming in Java The Walker School
Animation Mrs. C. Furman. Animation  We can animate our crab by switching the image between two pictures.  crab.png and crab2.png.
Chapter 6 - Interacting Objects: Newton’s Lab
Asteroids Games and Simulations O-O Programming in Java The Walker School The Walker School – Games and Simulations
Greenfoot Asteroids Mrs. C. Furman August 16, 2010.
Classes and Objects: Recap A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Classes and Objects  A typical Java program creates many objects which interact with one another by sending messages. Through the objects interactions,
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Games and Simulations O-O Programming in Java The Walker School
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 8 More Object Concepts
Chapter 3 Vector Class. Agenda Design and Implementation of Vector class – add, get, set remove, copy, equals, ensureCapacity Hangman using Vector class.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Java is an object oriented programming language In this model of programming all entities are objects that have methods and fields Methods perform tasks.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Chapter 10 Introduction to Classes
1 Warm-Up Problem Just like with primitive data types (int, double, etc.), we can create arrays of objects. ex: bankAccount employees[100]; Problem: It’s.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Lesson 6 – Libraries & APIs Libraries & APIs. Objective: We will explore how to take advantage of the huge number of pre-made classes provided with Java.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Newton’s Lab Games and Simulations O-O Programming in Java.
What is an object?. What Makes an Object? An object has identity (it acts as a single whole). Every object has a name that identifies what it is. Ex.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 4 - Finishing the Crab Game
Chapter 5 – Making Music: An On-Screen Piano (Part 1 – Using Loops)
More About Objects and Methods
Topic: Classes and Objects
More Sophisticated Behavior
Software Engineering Fall 2005
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Introduction to Object-oriented Program Design
Inheritance, Polymorphism, and Interfaces. Oh My
Dynamic Data Structures and Generics
Object Oriented Programming in java
Games and Simulations O-O Programming in Java The Walker School
Defining Classes and Methods
Presentation transcript:

Chapter 6 – Interacting Objects: Newton’s Lab

topics: objects interacting with each other, using helper classes, using classes from the Java library concepts: collection, list, for-each loop, standard class library  In this chapter, we shall investigate more sophisticated interactions between objects in a world. As a start, we shall investigate one of the most universal interactions between objects anywhere: Gravity.

Newton’s lab

Objects in Space The only non-abstract Actor-subclass of this scenario What kinds of bodies are in our solar system? Why don’t we see a “Sun” class? Why no “Planet” class? Open the Newtons-Lab-1 scenario from the book- scenarios folder. You will see that a world subclass already exists (called Space). We also have classes SmoothMover, Body, and Vector

Solar System The types of bodies in our solar system include planets, planetoids, moons, asteroids and comets. For our purposes we will consider each body only with regard to its color, size, mass, and the characteristics of its movement. This means that we can use abstraction to implement ONE class to handle every type of body.

The Space class: - 3 configurations of Space What happens when you activate one of these methods? Right-click on the Space world background

Space Public Methods Constructors within Constructors ?

Inspecting Body Methods Right – click on a body. What methods does it have?

Inspecting Body Properties Right click on a planet and inspect its properties. How does the object store its position?

Inspecting Body Properties Each Body holds a Vector object. What does the Vector object represent?

Helper Classes 2 Support Classes - SmoothMover - Vector SmoothMover is an Abstract class. Abstract classes do not have constructors. We will never place a “SmoothMover” on the board.

Helper Classes for Import Edit Menu / Import Class… Some Helper Classes Animal Counter GifImage Label Map Plotter ScoreBoard SimpleTimer SmoothMover Weather

More Helper (or Support) Classes Some Helper Classes AnimatedActor Counter Explosion FPS GifActor MidiPlayer Mover Plotter Rotator Slider

The SmoothMover Class A SmoothMover is an Object that stores and calculates its position as decimal numbers instead of integers. This allows for “smoother” and more precise movement. Each SmoothMover stores its movement as a Vector object. A Vector object stores direction and speed of movement.

Methods Inherited from SmoothMover SmoothMover objects have the same method (setLocation) twice. How do they differ? Why are they necessary?

Vectors Cartesian Representation: Two offsets (dx, dy) that determine how the position changes on a Cartesian Plane. Polar Representation: Change in position is defined by a direction and how far in that direction we move.

Vector Class Variables The Vector class implements BOTH Polar and Cartesian representation. All necessary conversions are handled within the class.

Method Inheritance Open and read SmoothMover and Vector. Which methods can we actually execute from the object menu? Every SmoothMover holds a Vector. Why can we not call Vectors methods from the menu?

Constructors A Constructor has no Return Type Specified A Constructor Always has the Same Name as the Class Constructor is Automatically Executed whenever an Instance (or object) of the Class is Created

Default Constructors Does not have any parameters. Makes it easy to create bodies interactively without having to specify details. This is a default constructor. What about the second constructor?

Default and non-Default Constructors The Body class has 2 constructors with different parameters. We call this an overloaded constructor Methods can have the same name, as long as their parameters are different. This means that the methods (or constructors) have different signatures.

this() and this. Invokes the non-default constructor with the specified values. There are two version of the variable “mass” in existence at this time. The Parameter “mass” and the class attribute “mass”. The “this.” means that we are assigning the value of the Parameter to the attribute and NOT the other way around.

Constants Means the value cannot be changed. Means it’s shared between all instances of this class. These variables are called constants. These variables do not change in a program.

Change act() so that it moves without applying any forces

Body Behavior Create multiple bodies. How do they behave?

Add Movement (Left) How would you make the body move left?

How to make objects go left?

/** * Construct a Body with default size, mass, movement and color. */ public Body() { this (20, 300, new Vector(180, 1.0), defaultColor); } Change the Direction in the Default Constructor from 0 to 180 Solution: Left Movement

Java Packages Programmers typically use packages to organize classes belonging to the same category or providing similar functionality. We can have a look at all the premade packages/classes of Java by selecting “Java Library Documentation” from the “Help”-tab. Imported using dot notation. import java.awt.Color;

Importing Java Color Library

 For example, every color is represented as a mixture of the three additive primary colors Red, Green, and Blue  Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value Representing Color

Color is expressed as an RGB (red-green-blue) value because our eyes have three types of color receptors that respond to light that has some amount of one of those three primary colors in it. The mixture of the different amounts of those three colors creates different colors. An RGB value of (255, 255, 0) maximizes the contribution of red and green, and minimizes the contribution of blue, which results in a bright yellow RGB Color Combinations

 A color in a Java program is represented as an object of the Color class  The Color class also contains several predefined colors, including the following: The Color class

 Other Predefined Colors: The Color class

You can define Custom Colors by declaring your own Color object with different RGB values as follows, where r,g,b are 3 values from 0 to 255: Color theColor = new Color(r,g,b); The above statement declares “theColor” to be an object variable (instead of a primitive variable) with Color as its type. The term “new” means that a new instance of the object will be created with the specified values. Custom Colors

Default Color of Body Calls the Color class. Sets the RBG values What is the legal range for colors?

Adding Gravitational Force

Apply Force To Do List To apply forces from all other Bodies to a Body, we will: a) Create a list containing all the Bodies currently in Space And b) Go through the list and apply the gravitational force of each of these bodies in sequence

Apply Force Algorithm Apply forces from other bodies: get all other bodies in space; for each of those bodies: { apply gravity from that body to our own; {

Apply Force – Part I Methods (and Variables) only intended to be called from within the class can be labeled private. When methods are intended to be called from outside the class, they should be labeled public.

Greenfoot World Methods Which methods give us access to objects within the world? We can have a look at all the Greenfoot-specific classes by selecting “Greenfoot Class Documentation” from the “Help”- tab.

Getting Objects (World Methods)  getObjects(java.lang.Class cls)  Gets a list of all objects in the world of a particular class.  getObjects(Body.class)  Gets a list of all objects of class Body in the world.  getObjects(null)  Keyword null is a special expression that means no object. This call will get a list of ALL object in the world.

Getting the Body Objects World getWorld() There is a method in the Actor class that gives us access to the World class. It signature is World getWorld() This method allows you to get access to all objects that have been added to your World. getWorld().getObjects(Body.class) Can be used from an actor to get all objects of class Body. It returns a java.util.List object. What is that?

Java.util.list What methods can be used to add items to a list? What methods can be used to remove items to a list? What methods can be used to find out how many items are in a list?

Lists can contain different types (or classes) of objects This notation tells us that a List is a generic type. Meaning a List has no data type itself. We provide the Data type by specifying it in the bracket. List …

Apply Force – Part II

For-Each Loops Helps to step through the items in a list. for (Type variableName : list) { statements; } You identify the variable type and name, then on the other side of the colon, you identify the list of values. Then the loop goes through the statements for each value in the list, using the variableName as an identifier for the object currently “in use”.

Apply Force – Part III Use an if-statement so that gravity is applied from all objects (bodies) in the list except the current object. “this” refers to the current object.

Applying Gravity

Apply Force Algorithm Apply forces from other bodies: get all other bodies in space; for each of those bodies: { apply gravity from that body to our own; {

Newton’s Law Newton's Law of Universal Gravitation states that every massive particle in the universe attracts every other massive particle with a force which is directly proportional to the product of their masses and inversely proportional to the square of the distance between them.

Apply Gravity Algorithm Apply gravity from object b) to object a) { calculate the distance between the x-/y- coordinate of the objects; create a new vector using this data to determine direction; calculate the distance between the two bodies using Pythagoras´ theorem; use Newton's formula to calculate the strength of the force calculate the length (acceleration) of the vector; apply the vector to object a); }

Acceleration = Force / Mass

Appling Gravity Method Why do these numbers need to be doubles?

Trying it Out Try out the three initializing methods from Space object again. What do you observe?

Experimenting with Gravity Change the gravity constant at the top of the body class. What happens? Change it by ½, change it by doubling it; change it by 1, change it by a decimal.

Experimenting with Mass & Movement Experiment with changes to the mass and/or initial movement of the bodies defined in the Body class. What happens? sizemassvectormovementxyrgb When experimenting it’s important to change one variable at a time.

Concept Summary