Chapter 3: Using Methods, Classes, and Objects
Chapter 3, Barron’s Text 2022-23
Overview
2
Method Calls and Placement
3
3
Method Calls and Placement
4
4
Figure 3-2 The First class with a call to the nameAndAddress()method
Method Calls and Placement
5
Figure 3-3 Placement of methods within a class
5
How to Define a Method
A method must include:
2. Method body
6
6
How to Define a Method
Place the entire method within the class that will use it, not within any other method
7
7
Access Specifiers
8
8
Where to Put Specifiers or Modifiers
Static is a non-access modifier. As are final, abstract etc.
9
9
Return Type
10
10
Method Name
11
11
Parentheses
12
12
Parameter List
13
13
Create a method with a single parameter:
14
14
Create a method with a single parameter:
15
15
Scope
16
16
Create a method with multiple parameters:
17
17
Create a method with multiple parameters:
18
Create a method that returns a value:
19
19
return Ends a Method
20
20
Methods Calling Methods
21
21
Overloading Methods
22
Overloaded Methods | Signature |
public int product(int n) {return n*n;} public double product(double x) {return x*x;} public double product(double x, double y) { return x*x; } | product(int) product(double) product(double, double) product(int, double) product(double, int) |
Objects vs Classes
Fish shark = new Fish();
23
23
How to Define a Class
24
24
Class Variables
25
25
Static vs Non-static Variables
26
Static Variables | Non-static (Instance) Variables |
accessed using class name ex. Math.PI | accessed using instance of a class ex. String s = “foo”; SOP(s.length); |
can be accessed by static and non static methods | cannot be accessed inside a static method. |
shared among all instances of a class. | are specific to that instance of a class. |
When you create a class with a static field and instantiate 100 objects, only one copy of that field exists in memory | When you create a class with a nonstatic field and instantiate 100 objects, then 100 copies of that field exist in memory. |
Static vs Non-static Methods
27
Static Methods | Non-static (Instance) Methods |
also called class methods | also called instance methods |
When you use a static field or method, you do not use an object; for example: JOptionPane.showDialog(); Math.pow(3,4); | When you use a nonstatic field or method, you must use an object; for example: System.out.println(); String s = “horse”; SOP(s.toLowerCase()); |
When you create a static method in a class and instantiate 100 objects, only one copy of the method exists in memory and the method does not receive a this reference. | When you create a nonstatic method in a class and instantiate 100 objects, only one copy of the method exists in memory, but the method receives a this reference that contains the address of the object currently using it |
final keyword
28
final boolean ARE_HORSES_COOL = true;
this keyword
this refers to the current object
Can be used
Most common usage
Call to this() must be the first statement in constructor.
29
class Foo{
int a;
int b;
Foo() { System.out.println(“Foo!”); }
Foo (int x) {
this(); // 3
System.out.println(x);
}
String toString(){
return this.a + “ ” + this.b; // 1
void moo(){
System.out.println(this); // 4
}
void spoo() {
this.moo(); // 2
}
}
this keyword
5. can be used to pass as argument in the constructor call useful if we have to use one object in multiple classes
6. can be used to return current class instance
30
class B{
A obj;
B(A obj){
this.obj = obj;
}
void display(){
System.out.println(obj.data);
}
}
class A{
int data=10;
A(){
B b = new B(this);
b.display();
}
public static void main(String args[]){
A a = new A();
}
}
class C{
C getC(){
return this;
}
void msg(){
System.out.println("Hello java");
}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Class Methods
31
31
Legal and Illegal Method Calls
32
32
Organizing Classes
class Foo {
// instance variables
// static variables
// constructors
// accessors and mutators
// additional methods
} // Foo
33
33
How to Declare an Object
Employee someEmployee;
someEmployee = new Employee();
or
Employee someEmployee = new Employee();
34
34
Ex. someEmployee.getRaise();
References
35
Primitive Data Types | Reference Data Types |
All built in data types ex. int, double, float | All objects and arrays ex. String, Random, int [] |
int num1 = 5;
int num2 = num1;
num1 = 10;
10
5
num1
num2
Both num1 and num2 have their own memory slots. If one is changed, the other is not affected.
Date d1 = new Date(5, 15, 2012);
Date d2 = d1;
5
5
d1
d2
Both d1 and d2 refer to the same location. If one is changed, the other is affected.
d1 and d2 are aliases
2012
month
day
year
References cont…
AddressBook ab;
if (ab == null)
ab = null;
36
Passing References as Parameters
main () {
A a1 = new A();
foo(a1);
}
void foo(A obj) {
obj.changeStuff();
}
37
obj and a1 are aliases of each other
changes to obj also affect a1
How to Achieve Encapsulation
38
38
Constructors
Employee chauffeur = new Employee();
39
39
Default Constructor
40
40
Sample Question 1
Consider the Date class:
Consider the following declarations:
Based on the given information, which of the following statements must be true?
Answer: F
The class would need to implement Comparable to have access to compareTo. Note: the AP Exam requires you to know what the compareTo method does, but not how to implement the Comparable interface
41
move this rectangle to see the answer
Sample Question 2
Consider the Card and Deck classes below, which are used to create a Deck of Card objects.
The programmer tests the constructor of the Deck class with the DeckTester class shown below.
When the code is run, a NullPointerException is thrown. Which of the following could be the cause of the error?
A) I only B) II only C) III only
D) 1 and II only E) II and III only
42
Practice
Do all the questions at the end of Chapter 3 in Barron’s Text
On AP Classroom: covered in Unit 3 Content
43
Sample Question 2 Solution
Answer: B
A NullPointerException is thrown whenever an attempt is made to call a method with an object that hasn’t been created with new. If the ArrayList deck was not created with new, the method call deck.add(someCard) would cause the NullPointerException.
Choice I is incorrect because DeckTester is an objectless class with a static main method, used to test objects in the program.
Choice III is wrong. No methods are called with a null Card object. If an attempt is made to add a Card to a deck without using the key word new, the compiler will find the error before the program is run.
44
Move this box to see answer.