Upload
julian-small
View
216
Download
0
Embed Size (px)
Citation preview
CHAPTER 8
A Second Look at Classes
and Objects
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
A note about coverage
• Say you have an if statement:
if (sunShining && temp > 75)
• You need 4 tests. sunShining T/F and temp > 75 and temp <= 75.
• If you can’t make 4 tests, you probably have something ahead that is making one of the conditions obsolete.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Quiz today
• Two parts– White paper – your individual answer – put these in
the folder when done. Make sure name is on.– Green paper – group responses – start only when
ALL of the individual papers are submitted.– Grades based on 40% individual effort and 60%
group. – 30 minutes total.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-4
Static Class Members
• Static fields and static methods do not belong to a single instance of a class.
• To invoke a static method or use a static field, the class name, rather than the instance name, is used.
• Example:
double val = Math.sqrt(25.0);
Class name Static method
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-5
Static Fields
• Class fields are declared using the static keyword between the access specifier and the field type.private static int instanceCount = 0;
• The field is initialized to 0 only once, regardless of the number of times the class is instantiated.– Primitive static fields are initialized to 0 if no initialization is
performed.
• Examples: Countable.java, StaticDemo.java
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-6
Static Fields
instanceCount field(static)
3
Object1 Object3Object2
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-7
Static Methods• Methods can also be declared static by placing the static
keyword between the access modifier and the return type of the method.public static double milesToKilometers(double miles)
{…}
• When a class contains a static method, it is not necessary to create an instance of the class in order to use the method.double kilosPerMile = Metric.milesToKilometers(1.0);
• Examples: Metric.java, MetricDemo.java
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-8
Static Methods
• Static methods are convenient because they may be called at the class level.
• They are typically used to create utility classes, such as the Math class in the Java Standard Library.
• Static methods may not communicate with instance fields, only static fields.