Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java Methods Objects and Classes Start on Slide 30 for day 2"— Presentation transcript:

1 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.

2 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.

3 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.

4 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.

5 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).

6 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) }

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

8 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.

9 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

10 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.

11 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) }

12 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.

13 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;

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

15 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.

16 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

17 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.

18 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

19 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.

20 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);

21 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.

22 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

23 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.

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

25 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

26 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.

27 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

28 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.

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

30 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’


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

Similar presentations


Ads by Google