Download presentation
Presentation is loading. Please wait.
1
Java Methods Objects and Classes
Much of this Powerpoint is taken from the Litvins Java methods book. Slide 24 on Tuesday Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Objects and Classes 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. 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
Constructors (cont’d)
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 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
Java Methods Chapter chapter9 = new Chapter(9);
A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Chapter chapter9 = new Chapter(9); This is a long and technical chapter: it deals with several important Java concepts and syntax details. Implementing Classes and Using Objects Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
23
Outline for the day Welcome back Take a look at BlueJ’s object bench
Online time to complete the Car class and driver Read about Object references Take a closer look at objects.
24
Java First OOP (or is that OOPS?)
Write a Car class. Include the following fields (Private data) Model Number of passengers Amount of gas Include the following methods Constructors Default and with the user sending initializing data addPassenger removePassenger fillTank outOfGas (Boolean function that returns true when the amount of gas is below 0.5) A toString method that returns a string with all of the field information. 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; public void addPassenger() ... Provide a driver file for the students to test their programs.
25
public class CarDriver {
// instance variables - replace the example below with your own public static void main (String [] args) Car car1 = new Car(); System.out.println(car1);//Calls the toString method of Car car1.addPassenger(); car1.fillTank(); Car car2 = new Car("Porsche", 2, 32); System.out.println(car2);//Calls the toString method of Car System.out.println("Car 2 out of gas " + car2.outOfGas()); } Driver for the Car class.
26
Objectives: Review public and private fields and methods
Learn the syntax for defining constructors and creating objects Learn the syntax for defining and calling methods Learn how parameters are passed to constructors and methods and how to return values from methods Learn about static and instance fields and methods These objectives are within the AP Java Subset for the A-level exam. Some of the details related to classes and methods are left out. Java is a big language.
27
Class’s Client Any class that uses class X is called a client of X. (We called it a driver for testing.) Class X private fields private methods Class Y A client of X public constructor(s) Constructs objects of X and/or calls X’s methods public methods The same programmer can develop a class and its client(s).
28
Public vs. Private Public constructors and methods of a class can be accesses by classes that use it — its clients. All fields are usually declared private — they are hidden from clients. Static constants occasionally can be public. “Helper” methods that are needed only inside the class are declared private. Static public constants (for example, Math.PI or Color.BLUE) do not violate the spirit of encapsulation because they are specifically intended to be used by the class’s clients.
29
Public vs. Private (cont’d)
A private field is accessible anywhere within the class’s source code. Any object can access and modify a private field of another object of the same class. public class Fraction { private int num, denom; ... public multiply (Fraction other) int newNum = num * other.num; num is private to the class Fraction. It is totally fine to refer to other.num in Fraction’s methods.
30
Accessors and Modifiers
A programmer often provides methods, called accessors, that return values of private fields; methods that set values of private fields are called modifiers. Accessors’ names often start with get, and modifiers’ names often start with set. These are not precise categories: the same method can modify several fields or modify a field and also return its old or new value. Thanks to accessors, you can change the type of a field or even the whole structure of fields but leave the class’s interface (public constructors and methods) unchanged. Modifiers also provide an opportunity to perform additional checks and make sure that fields are getting valid values. Create Accessors and Modifiers for each of the fields in the Car Class.
31
Accessor and Modifier Code Sample
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; public String getModel() //Accessor return model; public void setModel(String newModel) //Modifier model = newModel; … public class CarDriver { // instance variables - replace the example below with your own public static void main (String [] args) Car car2 = new Car("Porsche", 2, 32); System.out.println(car2);//Calls the toString method of Car System.out.println("Car 2 out of gas " + car2.outOfGas()); car2.setModel(“Chevy”); System.out.println(“Model “ + car2.getModel()); } Create Accessors and Modifiers for each of the fields in the Car Class.
32
Encapsulation Hiding the implementation details of a class (making all fields and helper methods private) is called encapsulation. Encapsulation helps in program maintenance: a change in one class does not affect other classes. A client of a class interacts with the class only through well-documented public constructors and methods; this facilitates team development. A programmer tries to minimize what others (clients) need to know about his or her class, even if he/she is “one of the others” when working on other classes. The idea is to keep things localized, so that if something changes in the implementation of one class, other classes remain unaffected. Programmers agree on the public interfaces (public constructors and methods) for their classes, then go to work on their classes and often test them separately, too.
33
Encapsulation (cont’d)
public class MyClass { // Private fields: private <sometype> myField; ... // Constructors: public MyClass (...) { ... } // Public methods: public <sometype> myMethod (...) { ... } // Private methods: private <sometype> myMethod (...) { ... } } Public interface: public constructors and methods The class’s public interface is what other programmers need to know to use the class. (They also might need to know some details about the class's superclass and the interfaces this class implements -- see Chapter 11).
34
Review: Matching Private
A method that is ‘only’ used by other methods inside the class. Public Hiding the implementation details of a class. No A client A method used to return values of private fields. Yes A method used to set values of private fields. What is a class called that uses another class? Are fields usually public or private? What is a “Helper” method? What is a modifier? What is an Accessor? Can you modify a private field of another object of the same class? What is ‘encapsulation’?
35
Constructors A constructor is a procedure for creating objects of the class. A constructor often initializes an object’s fields. Constructors do not have a return type (not even void) and they do not return a value. All constructors in a class have the same name — the name of the class. Constructors may take parameters. A constructor is invoked using the ‘new’ operator. A constructor cannot be called for a particular object, because that object does not yet exist. Constructors are invoked using the new operator, as explained shortly.
36
Constructors (cont’d)
If a class has more than one constructor, they must have different numbers and/or types of parameters. Programmers often provide a “no-args” constructor that takes no parameters (a.k.a. arguments). If a programmer does not define any constructors, Java provides one default no-args constructor, which allocates memory and sets fields to the default values. The default values for fields are as follows: 0 for numbers, false for booleans, and null for objects. Any constructor sets a field to the default, unless the field is explicitly set to some value. If a field is an object, a constructor may create that object by invoking a constructor for that object’s class.
37
What is the difference between these constructors?
public class Fraction { private int num, denom; public Fraction ( ) num = 0; denom = 1; } public Fraction (int n) num = n; } Continued public Fraction (int n, int d) { num = n; denom = d; reduce (); } public Fraction (Fraction other) num = other.num; denom = other.denom; ... “No-args” constructor This example shows four constructors for the Fraction class, including the no-args constructor and the copy constructor. Copy constructor
38
Be careful not to use method names that match the class names.
Constructors Be careful not to use method names that match the class names. A nasty bug: public class MyWindow extends JFrame { ... // Constructor: public void MyWindow ( ) } Compiles fine, but the compiler thinks this is a method and uses MyWindow’s default no-args constructor instead. It is an unfortunate decision in Java to allow a method name that is the same as the name of the class. Is this a constructor?
39
this represents the current object.
Constructors Constructors of a class can call each other using the keyword this — a good way to avoid duplicating code: public class Fraction { ... public Fraction (int n) this (n, 1); } ... public Fraction (int p, int q) { num = p; denom = q; reduce (); } If the structure of the fields change, only one constructor will have to be modified. Here we don’t gain much by using this, but in other situations where we have longer constructors that are almost identical, we can avoid duplicating a large chunk of code. Easier to debug and test, too. This usage of this is not in the AP subset. Calls another constructor with a Parameter list that matches this argument list.
40
Operator new Constructors are invoked using the operator new.
Parameters passed to new must match the number, types, and order of parameters expected by one of the constructors. public class Fraction { public Fraction (int n) num = n; denom = 1; } ... Fraction f1 = new Fraction ( ); Fraction f2 = new Fraction (5); Fraction f3 = new Fraction (4, 6); Fraction f4 = new Fraction (f3); The operator new returns a reference to (address of) the newly created object. 5 / 1
41
Operator new (cont’d) You must create an object before you can use it; the new operator is a way to do it. private Fraction ratio; ... ratio = new Fraction (2, 3); ratio = new Fraction (3, 4); ratio is set to null Now ratio refers to a valid object Java VM keeps track of how many variables refer to an object. Once this count becomes 0, the object is disposed of and its memory released. This is roughly how the automatic garbage collection mechanism works. Now ratio refers to another object (the old object is “garbage-collected”)
42
References to Objects f1 f1 f2 f2 Fraction f1 = new Fraction(3,7);
Fraction f2 = f1; Fraction f1 = new Fraction(3,7); Fraction f2 = new Fraction(3,7); A Fraction object: num = 3 denom = 7 A Fraction object: num = 3 denom = 7 f1 f1 f2 An assignment Fraction f2 = f1; does not create a copy of f1; it simply sets f2 to refer to the same object as f1 — two references refer to the same place in memory. A Fraction object: num = 3 denom = 7 f2 Refer to the same object
43
Review: Matching Constructor this new f1 = f2;
Fraction f1 = new Fraction(f2); Command that invokes the constructor method. Makes the Fraction object f1 equal the Fraction object f2. Used to refer to the current object. Makes the address of the f1 equal to the address of f2.
44
Methods To define a method: Body Header
public [or private] returnType methodName (type1 name1, ..., typeN nameN) { ... } Body Header To define a method: decide between public and private (usually public) give it a name specify the types of parameters and give them names specify the method’s return type or chose void write the method’s code A class may have private methods that are used within the class but are not callable from methods of other classes.
45
Methods (cont’d) A method is always defined inside a class.
A method returns a value of the specified type unless it is declared void; the return type can be any primitive data type or a class type. A method’s parameters can be of any primitive data types or class types. A method’s parameters of primitive data types are treated differently from parameters that are objects. More about this later. When a method that does not take any parameters is called, empty parentheses are required. Empty parentheses indicate that a method takes no parameters public [or private] returnType methodName ( ) { }
46
Methods: Java Style A method name starts with a lowercase letter.
Method names usually sound like verbs. The name of a method that returns the value of a field often starts with get: getWidth, getX The name of a method that sets the value of a field often starts with set: setLocation, setText Recall that if a name consists of several words, the second and subsequent words are capitalized. Like other variables, the names of method’s parameters start with lowercase letters.
47
Passing Parameters to Constructors and Methods
Any expression that has an appropriate data type can serve as an argument: double u = 3, v = -4; ... Polynomial p = new Polynomial (1.0, -(u + v), u * v); double y = p.getValue (2 * v - u); This applies to Boolean expressions, too. If an expression cannot be converted to the appropriate type (for example, if a method expects an int and the expression’s result type is a double), then the compiler reports an error. public class Polynomial { public Polynomial (double a, double b, double c) { ... } public double getValue (double x) { ... } ...
48
Passing Parameters (cont’d)
A “smaller” type can be promoted to a “larger” type (for example, int to long, float to double). int is promoted to double when necessary: ... Polynomial p = new Polynomial (1, -5, 6); double y = p.getValue (3); The compiler first looks for the exact match between the types of parameters in a call and the available methods; if there is no exact match but some parameters may be promoted to make a match, the compiler does that. The same as: (1.0, -5.0, 6.0) The same as: (3.0)
49
Passing Parameters (cont’d)
Primitive data types are always passed “by value”: the value is copied into the parameter. public class Polynomial { ... public double getValue (double u) double v; } copy double x = 3.0; double y = p.getValue ( x ); So, there is no way to write a swap(int x, int y) method in Java. A method cannot change the value of a variable (of a primitive data type) passed to it. Actually, this is not such a big limitation as it might first appear. If a method needs to change a variable’s value, that variable is usually a field in an object or an element in an array, and a reference to that object or array can be passed to the method. u acts like a local variable in getValue x: copy u:
50
Passing Parameters (cont’d)
public class Test { public double square (double x) x *= x; return x; } public static void main(String[ ] args) Test calc = new Test (); double x = 3.0; double y = calc.square (x); System.out.println (x + " " + y); x here is a copy of the argument passed to square. The copy is changed, but... It is OK stylistically to use the same name for a variable passed to a method as a parameter and for the method’s own formal parameter. Their scopes are different. The method treats its formal parameter as a local variable and can do whatever it wants to it -- the original value remains unchanged. ... the original x is unchanged. Output: 3 9
51
Passing Parameters (cont’d)
Objects are always passed as references: the reference is copied, not the object. Fraction f1 = new Fraction (1, 2); Fraction f2 = new Fraction (5, 17); Fraction f3 = f1.add (f2); public class Fraction { ... public Fraction add (Fraction f) } copy reference This is different from other languages, such as C++, where you can pass an object either “by value” (copy the whole object and pass the copy to the method), or “by reference” (pass the address of the same object to the method). In Java the object is NEVER copied into the parameter inside a method; instead, a copy of the reference is passed to a method. Still there is no way to write swap(SomeClass obj1, SomeClass obj2) in Java. If we try: private void swap(SomeClass obj1, SomeClass obj2) { SomeClass temp = obj1, obj1 = obj2, obj2 = temp; } this code only swaps copies of the references passed to it. Strictly speaking, references to objects are passed by value. A Fraction object: num = 5 denom = 17 refers to refers to the same object
52
Passing Parameters (cont’d)
A method can change an object passed to it as a parameter (because the method gets a reference to the original object). A method can change the object for which it was called (this object acts like an implicit parameter): The first situation is not very common: in a good OOP design a method is supposed to work on the object for which it is called, not an object passed to it as a parameter. The second situation is commonplace. An immutable object (as discussed in Chapetr 10) can never change. panel.setBackround(Color.BLUE);
53
Passing Parameters (cont’d)
Inside a method, this refers to the object for which the method was called. this can be passed to other constructors and methods as a parameter: public class ChessGame { ... Player player1 = new Player (this); The ChessGame object creates a Player object and passes to it a reference to this game (to let the player report its moves back to the game object). A reference to this ChessGame object
54
return Statement A method, unless void, returns a value of the specified type to the calling method. The return statement is used to immediately quit the method and return a value: return expression; So a return statement does two things: quits the method and (unless void) returns a value to the calling method. It is up to the calling method to decide whether it wants to use the returned value — sometype x = someMethod(...); — or ignore it: someMethod(...); The type of the return value or expression must match the method’s declared return type.
55
return Statement (cont’d)
A method can have several return statements; then all but one of them must be inside an if or else (or in a switch): public someType myMethod (...) { ... if (...) return <expression1>; else if (...) return <expression2>; return <expression3>; } If more than one return is unconditional, the compiler will report an “unreachable code” error.
56
return Statement (cont’d)
A boolean method can return true, false, or the result of a boolean expression: public boolean myMethod (...) { ... if (...) return true; return n % 2 == 0; } This possibility is often overlooked: a novice is tempted to write if (n % 2 == 0) return true; else return false; as opposed to simply return n % 2 == 0;
57
return Statement (cont’d)
A void method can use a return statement to quit the method early: public void myMethod (...) { ... if (...) return; } Some people insist on having only one return statement in a method (and having no return in a void method), but there is no real justification for that. There is nothing wrong with for (i = 0; i < n; i++) if (a[i] == target) return true; return false; No need for a redundant return at the end
58
return Statement (cont’d)
If its return type is a class, the method returns a reference to an object (or null). Often the returned object is created in the method using new. For example: The returned object can also come from a parameter or from a call to another method. public Fraction inverse () { if (num == 0) return null; return new Fraction (denom, num); } An example of the latter: public String makePrompt(String msg) { return String.toUpperCase(msg) + " ==>"; // toUpperCase is a static method in String that // returns a new string with all caps; // + means concatenation }
59
Your turn Add the following method to your Car class.
Return the amount of gas per passenger.
60
Overloaded Methods Methods of the same class that have the same name but different numbers or types of parameters are called overloaded methods. Use overloaded methods when they perform similar tasks: public void move (int x, int y) { ... } public void move (double x, double y) { ... } public void move (Point p) { ... } public Fraction add (int n) { ... } public Fraction add (Fraction other) { ... } Note that we talk about the types of the parameters, not their names.
61
Overloaded Methods (cont’d)
The compiler treats overloaded methods as completely different methods. The compiler knows which one to call based on the number and the types of the parameters passed to the method. public class Circle { public void move (int x, int y) { ... } public void move (Point p) ... Circle circle = new Circle(5); circle.move (50, 100); Point center = new Point(50, 100); circle.move (center); Ambiguity may still remain if the types do not match exactly. For example, if there are overloaded methods for (int,double) and for (double,int), and you call a method with (double,double), then the compiler reports an error.
62
Overloaded Methods (cont’d)
The return type alone is not sufficient for distinguishing between overloaded methods. public class Circle { public void move (int x, int y) { ... } public Point move (int x, int y) ... Syntax error It would be confusing, anyway. When a method is called, its returned value may be never used in the program, so the compiler would have no way of telling which version to call.
63
Non-Static Methods A non-static method is called for a particular object using “dot notation”: objName.instMethod(...); Non-static methods can access all fields and call all methods of their class — both static and non-static. vendor.addMoney(25); die1.roll(); Of course, the method’s code is not duplicated for each object but stored in static memory. But the local variables and the parameters passed to the method are dynamically allocated, usually on the system stack. When the method is exited, the stack space is released. The object for which the method is called basically serves as an implicit parameter passed to the method. The code obj.myMethod(x, y, z); is similar to: myMethod(obj, x, y, z); OOP uses the former syntax because it is more expressive and is needed for polymorphism.
64
Static Fields A static field (a.k.a. class field or class variable) is shared by all objects of the class. A non-static field (a.k.a. instance field or instance variable) belongs to an individual object. “Static” is basically a memory category. When a program is loaded, a chunk of memory is allocated to hold the program’s code and permanent data. This memory is called “static,” as opposed to the “dynamic” memory allocated for each newly created object. Dynamic memory is allocated and freed as objects are created and disposed of. If you have a constant that is the same for all objects of the class, there is no need to duplicate it in each object; instead you can declare this constant as static to store it once in static memory, together with the class’s code. Hence the term “static.” Instance variables are held in “dynamic” memory. “Static” is basically a memory category. When a program is loaded, a chunk of memory is allocated to hold the program’s code and permanent data. This memory is called “static,” as opposed to the “dynamic” memory allocated for each newly created object. Dynamic memory is allocated and freed as objects are created and disposed of. If you have a constant that is the same for all objects of the class, there is no need to duplicate it in each object; instead you can declare this constant as static to store it once in static memory, together with the class’s code. Hence the term “static.” Instance variables are held in “dynamic” memory.
65
Static Fields (cont’d)
A static field can hold a constant shared by all objects of the class: A static field can be used to collect statistics or totals for all objects of the class (for example, total sales for all vending machines) Reserved words: static final public class RollingDie { private static final double slowDown = 0.97; private static final double speedFactor = 0.04; ... The continuation of the Snack Bar lab is to add a static field that would keep track of the total sales for all machines.
66
Static Fields (cont’d)
Static fields are stored with the class code, separately from instance variables that describe an individual object. Public static fields, usually global constants, are referred to in other classes using “dot notation”: ClassName.constName Static fields are also called “class” fields because they belong to the whole class and you access them using the class’s name, not a particular object’s name. The latter is allowed (when the class can be instantiated) but it is bad style. double area = Math.PI * r * r; setBackground(Color.BLUE); c.add(btn, BorderLayout.NORTH); System.out.println(area);
67
Static Fields (cont’d)
Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods). If a class has only static fields, there is no point in creating objects of that class (all of them would be identical). Math and System are examples of the above. They have no public constructors and cannot be instantiated. If you initialize a static field in a constructor, it will be reset each time you create an object of the class. This defeats the purpose of a static field. Classes such as Math or System have no public constructors. Each has one private constructor to tell Java not to create a default public no-args constructor. A class like this cannot be instantiated: you cannot create instances (objects) of the class.
68
Static Methods Static methods can access and manipulate a class’s static fields. Static methods cannot access non-static fields or call non-static methods of the class. Static methods are called using “dot notation”: ClassName.statMethod(...) It is only natural that static methods cannot access instance variables: the latter belong to a particular object, and a static method doesn’t know which object to use. double x = Math.random(); double y = Math.sqrt (x); System.exit();
69
Static Methods (cont’d)
public class MyClass { public static final int statConst; private static int statVar; private int instVar; ... public static int statMethod(...) statVar = statConst; statMethod2(...); instVar = ...; instMethod(...); } Static method Again, instance methods and constructors can access all fields (both static and instance fields) and call all methods (both static and instance methods) of the class. Static methods can access only static fields and call only static methods. OK Errors!
70
Static Methods (cont’d)
main is static and therefore cannot access non-static fields or call non-static methods of its class: public class Hello { private int test () { ... } public static void main (String[ ] args) System.out.println (test ()); } Error: non-static method test is called from static context (main) If you want to call non-static methods or access non-static fields in main, you have to first create an object of the class, then call its methods or access its fields. The following will work: public static void main(String[] args) { Hello h = new Hello(); System.out.println(h.test()); } It is a bit of a paradox that main constructs the first object of the class of which it is a method. On the other hand, why not: main is a static method, so it doesn’t belong to any particular object.
71
Review: Are you allowed to define a class with no constructors?
Can a class have two different no-args constructors? What is a good style for naming constructors? What is the common Java style for method names? Are you allowed to define a class with no constructors? Yes. Then Java provides one default no-args constructor. Can a class have two different no-args constructors? No. Constructors must have different numbers or types of parameters. What is a good style for naming constructors? There is no choice: the names of all constructors are the same as the name of the class. What is the common Java style for method names? Start with a lowercase letter, with subsequent words capitalized. Methods should sound like verbs.
72
Review (cont’d): Are parameters of primitive data types passed to methods “by value” or “by reference”? Can a method have more than one return statement? Can a method have no return statements? Can a method create a new object and return it to the calling method? Are parameters of primitive data types passed to methods “by value” or “by reference”? By value. Can a method have more than one return statement? Yes, but all except one must be inside an if or else (or a switch). Can a method have no return statements? Yes, a void method doesn’t have to have a return. Can a method create a new object and return it to the calling method? Yes.
73
Review (cont’d): When is it appropriate to define overloaded methods?
Describe the difference between static and instance variables. What is the syntax for referring to a public static field outside the class? (Use ClassName as the name of the class and fieldOfDreams for the public static field.) When is it appropriate to define overloaded methods? When two methods perform similar tasks for different types or numbers of parameters. Describe the difference between class and instance variables. A class variable (declared static) is shared by all objects of the class; an instance variable may have different values in different objects. What is the syntax for referring to a public static field outside the class? ClassName.fieldName
74
Review (cont’d): Can non-static methods access static fields?
Can static methods access instance variables? Can static methods have local variables? Can non-static methods access static fields? Yes. Can static methods access instance variables? No. Static methods are not associated with any particular object, so how would they know which object’s instance variables to access? Can static methods have local variables? Sure, why not?
75
Information Overload Write what you recall about the following
Static Methods Static Fields Overloaded Methods Methods Constructors Time to Park the Car Rename it as YourNameCar and turn it in
76
Fractionally Better Program
Write the code for a Fraction Class Determine the Data, needed Determine the constructors needed Methods Add, subtract, multiply, divide Test your class using the Object Bench Write a Driver class for your Fraction Class
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.