Java Classes
General Information
Using Classes
A class can hold static fields and methods.
A class can also be a template to create instances,
these instances hold (non-static) fields and methods.
Instances are created by
new ClassName ()
new ClassName (args)
- static member field access, e.g, System.in, Math.PI
- static member method access, e.g, Integer.parseInt(String s)
or Math.atan2 (double y, double x)
- instance member field access
(public fields are discouraged, so you won't find examples in the Java libraries).
- instance member method access, e.g., str.length()
Arbitrary-Precision Math
A case study in using existing classes.
Examples of creating BigInteger and BigDecimal values
BigInteger bi;
bi = BigInteger.valueOf (1);
bi = new BigInteger ("123456789ABCDEF", 16);
BigDecimal bd;
bd = new BigDecimal ("-2.71828")
bd = new BigDecimal ("1.23E-23")
Examples of BigInteger
Classes as data structures
When using a class as a template
fields
methods
constructors
- SimpleTime0.java
- SimpleTime1.java
- TimeMain.java
This program consists of more than one user-provided class:
javac SimpleTime1.java
javac TimeMain.java
java TimeMain
The class file records the dependency of TimeMain on SimpleTime and java
searches the class path to (dynamically) load SimpleTime.class.
Notice the use of new -- class instantiation -- in TimeMain.java.
- High-level structure of the program.
- Instantiation (van der Linden, page 93):
- The memory for the object is allocated.
- The memory is cleared, causing data fields to be filled with
the default values zero, 0, null, U+000, and so on.
All objects start with particular, legal state.
- The constructor method is called and might explicitly call another
constructor in the same class with this(...).
- Eventually a constructor in the object's parent class must be called,
either explicitly with super(...), or implicitly.
It's parent's constructor is also called and so on all the way back
to java.lang.Object
- And data fields with explicit initializers have
those initial assignments execute
in the order they occur in the class.
- Any instance initializers are executed. (These are provided for anonymous
classes.)
- The statements after
this(...) or super(...) (if either is present)
are executed.
- Notice no pointers (instances are always implicitly references).
- The default no-arg constructor.
SimpleTime1b.java
- SimpleTime2.java
- SimpleTime3.java
- SimpleTime4.java
- SimpleTime5.java (immutable)
- SimpleTime6.java (equality)
Simple, complete classes as data structures.
Point2D.java,
Circle.java, and
Line.java.
Also:
Polynomial.java,
Person.java, and
Elephant.java
- Body1.java --
a program using a recursive class with a classwide (static) variable, no user-defined constructors
- Body2.java --
a program using a recursive class with user-defined constructor
- Body3.java --
a program using a recursive class with multiple, user-defined constructors
- Body4.java --
explicit constructor invocation of another constructor in the same class
using this
- Body5.java --
immutable class. NB can't create cycles (maybe a good thing, maybe a bad thing).
- Body6.java --
circular data requires the capacity to update the data structure later
Classes as simulation.
BankAccount.java,
Image.java,
Aircraft.java
Enumeratation Types
Examples:
Main.java, and
Card.java.
enum Direction {
RD(+2,-1), RU(+2,+1), LU(-2,+1), LD(-2,-1),
UL(-1,+2), UR(+1,+2), DL(-1,-2), DR(+1,-2);
private int dx,dy;
Direction (int dx, int dy) { this.dx=dx; this.dy=dy; }
public final Square move (Square p) {
return new Square (p.x+dx,p.y+dy);
}
}
Methods (Subprocedures)
Methods can be both static and instance (not static).
Actual Arguments, Formal Parameters
Definitions: actual arguments, formal parameters.
System.out.println ("n=" + n);
(the actual argument is in red)
void method (final int arg) {
final int s = arg+arg;
}
(the formal parameter is in red)
§ 8.4.1 Formal Parameters.
- "If two formal parameters of the same method or constructor are declared to have the same name, then a
compile-time error occurs."
- "These parameter names may not be redeclared as local variables of the method,
or as exception parameters of catch clauses in a try statement of the method or constructor."
- "It is a compile-time error if a method or constructor parameter that is declared
final is assigned to within the body of the method or constructor."
Examples of these three errors
Errors.java,
Overloading
- If two methods of a class have the same name but different signatures,
then the method names is said to be overloaded.
Simple.java,
- An example is in the
class.
The method sort is overloaded.
final int[] ai = {4, 5, 1};
final double[] ad = {4.0, 5.0, 1.0};
final char [] ac = {'a', 'ô', 'ß'};
Arrays.sort (ad);
Arrays.sort (ai);
Arrays.sort (ac);
- Another example is in the
class.
The method print is overloaded.
See
PrintMain.java
- User can overload methods, too.
See
Inc.java
- Overloaded methods don't have to be static.
class Main {
int i;
public StringtoString () {
return Integer.toString (i);
}
public String toString (int base) {
return Integer.toString (i, base);
}
}
- Constructors, like methods, can be overloaded.
- Overloading is allowed if the number of parameters or types of parameters
are different; return types are not considered (unlike Ada).
Main.java
- More examples.
Print.java, and
Min.java.
- overload resolution and numeric promotion
Numeric.java,
Promote.java.
Determine Method Signature
from the Java Language Specification.
- overloading and subclasses
(Overload.java)
Can overload even if parameter types are subclasses.
The method invoked is determined at compile-time.
Parameter Passing
- parameter passing.
When a method is invoked, the values of the actual argument expressions
are used to initialize newly created parameter values.
This is called "call-by-value."
- Immutable objects cannot be changed, ipso facto they cannot be changed
when passed as parameters.
The Java class
.
contrasted with the class
.
PassString.java
final StringBuffer sb = new StringBuffer ("abcd");
Mangler.method (sb); // copy value(?) into new formal
if (sb.equals (new StringBuffer ("abcd"))) {
System.out.println ("");
} else {
System.out.println ("Someone mangled my string!");
}
The value copied is the reference; not the object.
(Immutable objects can be shared without negative consequences.)
Compile Time Checking
[Where does this all belong?]
Practically no compiler warnings in Java.
final
See "§ 4.5.4 final Variables" in the Java Language Specification
A variable can be declared final. A final variable may only be assigned to once.
It is a compile time error if a final variable is assigned to
unless it is definitely unassigned (§16) immediately prior to the assignment.
A blank final is a final variable whose declaration lacks an initializer.
Single assignment
Constructors
Definite Assignment
"Chapter 16: Definite Assignment" in the Java Language Specification
void flow(boolean flag) {
int k;
if (flag) k = 3;
else k = 4;
System.out.println (k); // k is "definitely assigned" before here
}
void flow(boolean flag) {
int k;
if (flag) k = 3;
if (!flag) k = 4;
System.out.println (k); // k is not "definitely assigned" before here
}
Unreachable
"§ 14.20 Unreachable Statements" in the Java Language Specification
It is a compile-time error if a statement cannot be executed because it is unreachable. Every Java compiler must carry out the conservative flow analysis
... to make sure all statements are reachable.
Shadow
Scope.java
Order of Initialization
static blocks, order of initialization [goes else where!]
Bad.java
Three.java
Order.java
Classes and inheritance
- The Java class
.
Top of the class hierarchy, toString, equals, notify, wait, etc.
class Object {
public boolean equals (Object obj) // ...
public String toString () // ...
protected Object clone() // ...
public void wait() // ...
public void notify() // ...
}
Single inheritance. Every class has exactly one parent (except Object).
class MyClass { class MyClass extends Object {
// ... // ...
} }
- A hierarchical structure like a tree --- no cycles!
class A extends B {}
class B extends A {}
- extends, inheritance
class Base { int x; }
class Derived extends Base {int y; }
Class Derived inherits y
Derived d = new Derived ();
d.x = 3
Methods also.
class Base {
int m1 (char c) {return c-'A';}
}
class Derived extends Base {
int m2 (double d) {return (int)Math.round(d);}
}
class Main {
void main () {
Derived d = new Derived();
int i = d.m1 ('D');
}
}
- Subclass polymorphism
Poly.java,
- [Need an example of instanceof.]
- Casting (widening, narrowing)
ClassCast.java.
Subclassing (widening), super in constructor, narrowing and instanceof,
field hiding and static access.
Subclass.java
- overriding
OO Programming
NonOO.java,
Tip -- Use of instanceof may indicate non OO programming.
Simple.java
Tip -- Always use @Override.
Note -- @Override does not cause a method to
be overridden; its asks the compile to check.
- Dispatch.java --
dynamic dispatch of methods.
Calling may be expensive because of the indirection.
- §15.11.2 Accessing Superclass members using super.
AccessField.java
- §15.12.4.9 Method invocation using super.
AccessMethod.java --
casting makes no difference in accessing methods.
"the instance method to be invoked is chosen according to the run-time
class of the object referred to be this.
A cast does not change the class of an object;
it only checks that the class is compatible with the specified type.
- Methods are overridden on a signature-by-signature basis.
If, for example, a class declares two methods with the same name,
and a subclass overrides one of them, the subclass still
inherits the other methods.
In this respect, Java differs from C++.
- Test.java --
subclass contract is honored
- hiding instance variables and hiding static methods
StaticTest.java
- Method access in superclasses.
- Inheritance: instances of subclasses can be used as if they are instances of the superclass.
class Vehicle {}
class Car extends Vehicle {}
Vehicle x = new Car (); // A car "is a" vehicle
Vehicle[] vehicles = {new Car(), new Vehicle(), new Car(), new Vehicle()};
for (int i=0; i<vehicles.length; i++) {
System.out.println (vehicles[i]);
}
- Losing type information:
Widening.java
Absence of generics (templates) makes this sort of program inevitable.
- ProtectedMain.java;
ProtectedMethod.java
- Sub.java --
subclasses and arrays
Modifiers
Access modifiers
At most one of:
- public -- no restrictions
- protected -- class it subclasses
- private -- class only
The absence of any access modifiers indicates "package" access.
See the discussion after packages.
Class modifiers
See § 8.1.1 Class Modifiers
- At most one of the access modifiers public, protected (member classes only), private (member classes only)
- abstract -- subclass' responsibility to provide one or more method bodies;
the class cannot be instantiated
- static -- (member classes only)
- final -- subclassed not allowed to extend it. Implicitly all
methods are final. This can be a performance gain as the methods can
be in-lined or statically determined.
- strictfp --
"Within an expression that is not FP-strict,
some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a
calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow."
Field modifiers
See § 8.3.1 Field Modifiers
- At most one of the access modifiers public, protected, private
- final -- assigned to
- static -- shared by all instances, classwide
- transient -- these fields discarded when saved to persistent storage
- volatile -- allows threads to keep a private working copying, but must
reconcile at every access.
Method modifiers
See § 8.4.3 Method Modifiers
- At most one of the access modifiers public, protected, private
- abstract -- subclass' responsibility to provide a method body
- static -- class method invoked without requiring a reference to a particular object
- final -- subclassed not allowed to overrided or hide it
- synchronized -- a lock is required before it executes
- native -- implemented in platform-dependent code
- strictfp --
"Within an expression that is not FP-strict,
some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a
calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow."
final modifier
To summarize the uses of the final modifier on fields, methods, classes and more:
- local declarations -- assigned to once in the method
- formal parameters -- not assigned to at all in the method
- fields -- assigned to once in the class
- methods -- can't be overridden.
See BadFinal.java
- classes -- can't be subclassed
See BadFinal.java again.
The following usage notes:
- fields in interfaces (introduced later) must be final.
Declaring them as such is redundant and discouraged by the language authors.
- "A compile-time error occurs if a final variable is also declared volatile."
It would be pointless to keep in sync a value that does not change.
Abstract classes
Interfaces
See chapter 9: Interfaces
in the Java Language Third, Second Edition
- Verbose.java --
a simple interface for sharing information among classes.
[Avoid using fields in interfaces.]
- List.java --
unrelated classes can be used polymorphically.
- Example.java --
implementing multiple interfaces.
- Repeat.java --
an interface for string-like structures: String, StringBuilder, and repeated strings.
- Sorting
- Employee01.java --
sort using an abstract class
- Employee02.java --
sort using an interface
- PointPack.java
- Reactive.java
(uses threads and member classes)
- Main.java
uses the predefined interfaces
,
.
,
java.util.SortedSet,
and collection class java.util.TreeMap.
The output.
Some important interfaces:
- The Java interface
.
- The Java interface
.
- The Java interface
.
- The Java interface
.
- The Java marker interface
.
- The Java marker interface
.
Nested classes
"A nested class is any class whose declaration occurs within the body of another class or interface.
A top level class is a class that is not a nested class."
--- from chapter 8 Classes
in the Java Language Specification, Third Edition.
"A member class is a class whose declaration is directly enclosed
in another class or interface declaration."
--- from the section Member Type Declarations.
"An inner class is a nested class that is not explicitly or implicitly declared static."
--- from the section 8.1.2 Inner Class and Enclosing Instances.
--- from the section 8.1.3 Inner Class and Enclosing Instances.
- Nest.java
-- nested top-level inner class.
- Local.java
-- local
- Iter.java is similar in that
a method returns a local class.
- Anon.java --
anonymous member class and the interface java.io.FilenameFilter
- Searcher.java --
An anonymous member class and a user-defined interface.
- Perm.java --
member classes, Comparator, Iterator, HashMap, ArrayList.
The output.
Ryan Stansifer <ryan@cs.fit.edu>
Last modified: Fri Sep 16 09:48:44 EDT 2011