Java Methods Objects and Classes Start on Slide 30 for day 2

Slides:



Advertisements
Similar presentations
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Java Basics M Taimoor Khan
Road Map Introduction to object oriented programming. Classes
Fall 2007ACS-1903 BlueJ Ron McFadyen Lab 1: Using BlueJ at UofW The purpose of this lab is to give you some experience with BlueJ. Over the course of the.
Objects Interaction and Source Code Week 2. OBJECT ORIENTATION BASICS REVIEW.
Chapter 3 - Introduction to Java Applets Outline 3.1Introduction 3.2Thinking About Objects 3.4A Simple Java Applet: Drawing a String 3.5Two More Simple.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
Introduction to Programming Writing Java Beginning Java Programs.
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.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Introduction to Java. 2 Textbook David J. Barnes & Michael Kölling Objects First with Java A Practical Introduction using BlueJ Fourth edition, Pearson.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 (part 2) Khalid Siddiqui.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
Introduction to Programming Writing Java Beginning Java Programs.
AP Computer Science A – Healdsburg High School 1 Unit 3 - Objects and Classes Lab: First Steps - Example.
Inheritance A Review of Objects, Classes, and Subclasses.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Object Oriented Programming Object and Classes Lecture 3 MBY.
CS 112 Introduction to Programming Java Graphics Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Console Input and Output JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Variables in Java A variable holds either
Concepts of Object Oriented Programming
Java Classes, Objects, and Events: A Preview
Classes and OOP.
Object Oriented Programming
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3: Using Methods, Classes, and Objects
CSC240 Computer Science III
Java LESSON 7 Objects, Part 1
Java Methods Objects and Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Variables ICS2O.
Chapter 9 Objects and Classes
Java Methods Objects and Classes Start on Slide 30 for day 2
Applying OO Concepts Using Java
Session 2: Introduction to Object Oriented Programming
Packages & Random and Math Classes
Object Oriented Programming in java
Classes CS 21a: Introduction to Computing I
Classes, Objects and Methods
Presentation transcript:

Java Methods Objects and Classes Start on Slide 30 for day 2 Much of this Powerpoint is taken from the Litvins Java methods book. Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Objects and Classes Start on Slide 30 for day 2 The First Steps case study in this chapter is rich enough to illustrate the main OOP concepts and give students some material for fun exercises.

Objectives: See an example of a small program written in OOP style and discuss the types of objects used in it Learn about the general structure of a class, its fields, constructors, and methods Get a feel for how objects are created and how to call their methods Learn a little about inheritance in OOP This chapter gives an introduction to the main Java and OOP concepts but does not require their full understanding. In terms of grasping the big picture, each student proceeds at his or her own pace. The same concepts are covered later in more depth. Here students get a general idea of how things are put together, get a feel for OOP, and work on exercises that require rearranging small pieces of code.

Object Oriented Programming: OOP An OO program models the application as a world of interacting objects. An object can create other objects. An object can call another object’s (and its own) methods (that is, “send messages”). An object has data fields, which hold values that can change while the program is running. A role play exercise may help students grasp the notion of objects and methods.

Objects A software bundle of related variables and methods. Can model real-world objects Can represent software entities (events, files, images, etc.) It is kind of like a turbo-charged Pascal Record. It not only contains the different fields of data, it also contains code. In Java, numbers and characters are not objects but there are so-called wrapper classes Integer, Double, Character, etc., which represent numbers and characters as objects.

Classes and Objects A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain type. Similar to a type declaration in Pascal An object is called an instance of a class. A program can create and use more than one object (instance) of the same class. (This process is also called instantiation.) Creation of an object is called instantiation (of its class).

public class SomeClass SomeClass.java import ... import statements public class SomeClass Class header { Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects Fields Constructors Methods Methods for constructing a new object of this class and initializing its fields Some programming languages (Pascal, for example) distinguish between functions and procedures. A function performs a calculation and returns the resulting value. A procedure does something but does not return any value. In Java, a method that returns a value is like a function; a method that is declared void does not return any value, so it is like a procedure. A constructor is special procedure for constructing an object. It has no return value and it is not even declared void. Other than that, constructors are similar to methods. Actions that an object of this class can take (behaviors) }

Classes and Source Files Each class is stored in a separate file The name of the file must be the same as the name of the class, with the extension .java public class Car { ... } Car.java By convention, the name of a class (and its source file) always starts with a capital letter. In the Unix operating system, where Java started, file names are case-sensitive. In Windows the names can use upper- and lowercase letters, but names that differ only in case are deemed the same. But javac and java still care. Note that in command-line use of JDK, javac takes a file name SomeThing.java, while java takes a class name SomeThing (no extension). We will talk more about stylistic conventions vs. the required Java syntax in Chapter 5. (In Java, all names are case-sensitive.)

Libraries Java programs are usually not written from scratch. There are hundreds of library classes for all occasions. Library classes are organized into packages (folders.) For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — GUI development package Go to Java API docs and examine the list of packages in the upper-left corner. We will mostly use classes from java.lang, java.util, java.awt, java.awt.event, javax.swing, and java.io.

import Full library class names include the package name. For example: java.awt.Color javax.swing.JButton import statements at the top of the source file let you refer to library classes by their short names: import javax.swing.JButton; ... JButton go = new JButton("Go"); A package name implies the location of the class files in the package. For example, java.awt.event implies that the classes are in the java/awt/event subfolder. In reality, packages are compressed into .jar files that have this path information for classes saved inside. A .jar file is like a .zip file; in fact, it can be opened with a program that normally reads and creates .zip files (for example, rename x.jar into x.zip). import is simply a substitution directive that says: Whenever you see JButton, treat it like javax.swing.JButton. No files are moved or included. If you want a parallel to C++, import is more like #define than #include. Fully-qualified name

import (cont’d) You can import names for all the classes in a package by using a wildcard .*: import java.awt.*; import java.awt.event.*; import javax.swing.*; java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes. Imports all classes from awt, awt.event, and swing packages Some programmers do not like .* and prefer to list all imported classes individually. Once the number of library classes used becomes large, this becomes too tedious. It is also harder to change the class: you need to add import statements for each library class added.

public class SomeClass SomeClass.java import ... import statements public class SomeClass Class header { Attributes / variables that define the object’s state; can hold numbers, characters, strings, other objects Fields Constructors Methods Procedures for constructing a new object of this class and initializing its fields Some programming languages (Pascal, for example) distinguish between functions and procedures. A function performs a calculation and returns the resulting value. A procedure does something but does not return any value. In Java, a method that returns a value is like a function; a method that is declared void does not return any value, so it is like a procedure. A constructor is special procedure for constructing an object. It has no return value and it is not even declared void. Other than that, constructors are similar to methods. Actions that an object of this class can take (behaviors) }

Fields A.k.a. instance variables Constitute “private memory” of an object Each field has a data type (int, double, String, Image, Foot, etc.) Each field has a name given by the programmer In Java, fields represent attributes of an object.

Fields (cont’d) private [static] [final] datatype name; You name it! Fields (cont’d) private [static] [final] datatype name; Usually private int, double, etc., or an object: String, Image, Foot May be present: means the field is shared by all objects in the class. Does not need to be made into an object to use it. Constant: May be present: means the field is a constant More on syntax for declaring fields in Chapter 6. Programmers strive to make their programs readable. One of the important tools in this struggle is to give meaningful names to classes, fields, variables, and methods: not too short, not too long, and descriptive. private int numberOfPassengers;

Example: Fields/ Instance Variables public class Car { private String model; private int numberOfPassengers; private double amountOfGas; }

Constructors Short methods for creating objects of a class Always have the same name as the class Initialize the object’s fields May take parameters A class may have several constructors that differ in the number and/or types of their parameters. (Polymorphism) It is usually a good idea to provide a so-called “no-args” constructor that takes no parameters (arguments). If no constructors are supplied at all, then Java provides one default no-args constructor that only allocates memory for the object and initializes its fields to default values (numbers to zero, booleans to false, objects to null). A class may have only one no-args constructor. In general, two constructors for the same class with exactly the same number and types of parameters cannot coexist.

Constructors (cont’d) The name of a constructor is always the same as the name of the class public class Car { private String model; private int numberOfPassengers; private double amountOfGas; public Car (String name, int pass, double gas) model = name; numberOfPassengers = pass; amountOfGas = gas; } ... A constructor can take parameters Fields that are not explicitly initialized get default values (zero for numbers, false for booleans, null for objects). Initializes fields

Constructor Rules It is usually a good idea to provide a default or “no-args” constructor that takes no parameters (arguments). If no constructors are supplied at all, then Java provides one default no-args constructor that only allocates memory for the object and initializes its fields to default values (numbers to zero, booleans to false, objects to null). A class may have only one no-args constructor. In general, two constructors for the same class with exactly the same number and types of parameters cannot coexist.

CarTest.java and Car.java need to be in the same Project (Folder) Constructors An object is created with the new operator // CarTest.java ... Car firstCar = new Car (“Yugo”, 0, 5.0); public class Car { private String model; private int numberOfPassengers; private double amountOfGas; public Car (String name, int pass, double gas) ... } The number, order, and types of parameters must match If a class has several constructors, new can use any one of them. Constructor

Default Constructor: No parameters public class Car { private String model; private int numberOfPassengers; private double amountOfGas; public Car () model = “”; numberOfPassengers = 0; amountOfGas = 0.0; } public Car (String name, int pass, double gas) model = name; numberOfPassengers = pass; amountOfGas = gas; ... Default constructor. No parameters If you have multiple constructors, they must have different numbers and/or types of parameters.

Calling different constructors public class Car { private String model; private int numberOfPassengers; private double amountOfGas; public Car () model = “”; numberOfPassengers = 0; amountOfGas = 0.0; } public Car (String name, int pass, double gas) model = name; numberOfPassengers = pass; amountOfGas = gas; ... // CarTest.java ... Car secondCar = new Car(); Car firstCar = new Car (“Yugo”, 0, 5.0);

Review: Match the following Class Constructor Object private static final Instance variables import Constant Can be used by methods inside the object only Can be used without creating an object Used to tie to libraries of classes. Used to create (instantiate) an object. A blueprint for making objects. Fields, the data part of an object. An instance of a class. A quick review of the concepts covered so far.

Copy and Open the Shapes Project Copy the Shapes folder from the Assignments Folder into your AP Java Folder. From BlueJ, Open the Shapes Project. File Open Project Double Click on ‘Shapes’ Open the ‘Circle’ class

Where is the constructor? What, if any, parameters are there? public class Circle { private int diameter; private int xPosition; private int yPosition; private String color; private boolean isVisible; public Circle() diameter = 30; xPosition = 20; yPosition = 60; color = "blue"; isVisible = false; } public Circle(int sentDiameter) diameter = sentDiameter; xPosition = 20; yPosition = 60; color = "blue"; isVisible = false; public void makeVisible() isVisible = true; draw(); private void draw() if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.draw(this, color, new Ellipse2D.Double(xPosition, yPosition, diameter, diameter)); canvas.wait(10); }… What is the class name? Where is the constructor? What, if any, parameters are there? Are there any instance variables? If so, what are they? How can you find the constructor? What else is in the class? The name of the constructor is the same as the name of the class, so it starts with a capital letter. The programmer gives names to fields and methods. Style: by convention, the names of methods and fields start with a lowercase letter. Names of fields should sound like nouns, and names of methods should sound like verbs.

Review What do you recall about Constructors Methods new Calling a method Application Instance variables private public

Experimenting with Previously Written Methods: Circles and the Object Bench Calling the constructor. Create circles Right click on the class Circle Select ‘new Circle()’ Give the circle a name

Looking at Methods from the Object Bench Right click on the object you have just created. Try makeVisible(), makeInVisible() Experiment with the other methods to manipulate the object. Make other circles. Make other objects.

Make a drawing Make a house with a sun, roof, and window Make a… turkey, hedgehog, tennis racket, robot, baseball field, beaver, thanksgiving scene,… Demo to Smith

Under construction Open the Shapes class and add constructors for the Circle, Square and Triangle classes. Circle: For entering the radius Circle: For entering the x and y coordinates of the point Circle: Add Radius, x, and y coordinates Square: Size Square: X and Y coordinates Square: Size, X and Y coordinates. Triangle: X and Y Coordinates Traingle: Height, Width, X and Y coordinates. Test your constructors using the object bench.

Review What do you recall about Constructors Methods new Calling a method Application Instance variables this private public

Writing an Application to Make Objects Class Name. This defines the object that is created. Class name. This defines the type of the pointer (reference). public class Drawing { public static void main(String [] args) Circle pumpkin = new Circle(); pumpkin.makeVisible(); Square smith = new Square(); smith.makeVisible(); Circle sun = new Circle(10); sun.makeVisible(); } After the object is created, you can call the public methods of object that were defined in the class. Create an Application to make a scene or a drawing using objects of the previous defined classes. Label it ‘yournameSceneApp’