Download Lecture - Java - Massey University

Document related concepts
no text concepts found
Transcript
159.234 LECTURE
26
JAVA
Introduction
1
Introduction to Java
• This section is intended as a rapid introduction to
programming in the Java programming language and
environment, focusing on the core language features.
• A number of worked example programs will be used as the
main vehicle for exposition of the Java programming
language features.
• The API's for the various packages will not be covered in
detail.
• This course does not cover the topics of Networking or
Threads.
2
The Java Programming Language
http://java.sun.com
developed by James Gosling at Sun Microsystems in the early 90’s
“Write once, run anywhere”
Platform independent programs with features such as graphics,
audio, video, and Internet connectivity.
ideal for developing secure, distributed, network-based end-user
applications in environments ranging from network-embedded
devices to the World-Wide Web and the desktop.
Language and Environment
• Java is a programming language definition and an
environment (J2SE SDK)
• As a language: Object Oriented, multi-threaded;
dynamic loading; code checking for security and type
safety.
• Large growing set of utilities and other library
packages in accompanying development kit.
4
The Java Programming Language
http://java.sun.com
Source code is compiled into its corresponding
generic bytecode language
Java Virtual
Machine – a
program that runs the
bytecode
There’s a JVM for any Computer + Windows, Sun Solaris, Linux, Macintosh, etc.
Elements of Java
Netscape, Internet Explorer, Mozilla come bundled with the JVM.
Source codes and bytecodes are independent of the type of computer system.
Web page
Instructions to load a
Java program
Web Browser
JVM
Browser automatically downloads
the bytecode file and runs the JVM on it.
6
Elements of Java
All Java programs are compiled to execute on a
Java Virtual Machine (Java VM)
Special machine language
known as bytecode
Java VM is simulated by a special program
called Java Runtime Environment (JRE)
A version of JRE has been created for
each Computer + OS combination.
JRE loads and verifies the bytecode to make
sure that the program is valid.
bytecode is independent of any
particular computer hardware.
JRE runs a Java Interpreter or possibly a just-in-time compiler (JIT) that
converts the bytecode into the machine code of the particular computer
JRE
e.g. scite
Java
Compiler
Editor
MyProgram.java
Java
Interpreter
MyProgram.class
bytecode
7
Elements of Java
1. Java Programming Language
2. Java Runtime Environment
3. Java Application Programming Interface
(API)
one time
only
Editor
every time
Java
Compiler
MyProgram.java
Java
Interpreter
MyProgram.class
bytecode
Tailored for a
specific computer
8
The Java Virtual Machine
• Java Virtual Machine (JVM) constitutes:
– the Run Time Environment (RTE)
– Garbage Collector (GC) - as a separate thread
– Security model
• JVM defines the:
–
–
–
–
–
–
Class file format
the register set
the Stack
Instruction set
Garbage collected heap
Memory area
9
‘Hello, World!’ Example
A simple application
Comments
/*
This program prints out “Hello, World!” on the standard
output and quits. It defines a class “HelloWorld” and a
“main” method within that class
Class Definition
Method
Definition
Executable
Statement
*/
public class HelloWorld{
//Define the main method
public static void main( String args[] ) {
System.out.println(”Hello World!"); //print line
}
}
A Java application consists of one or more classes defining data and methods.
10
‘Hello, World!’ Example
Every Java application must have at least one user-defined class, and that class
must contain a method named main, which is where the program starts
executing.
Simplest possible Java application :
- single class with single method main.
Comments
/*
This program prints out “Hello, World!” on the standard output and
quits. It defines a class “HelloWorld” and a “main” method within
that class
Class Definition
Method
Definition
Executable
Statement
*/
public class HelloWorld{
//Define the main method
public static void main( String args[] ) { //must appear in every Java
//application
System.out.println(”Hello World!"); //print line
}
11
}
‘Hello, World!’ Example
Filename: HelloWorld.java
To compile: javac HelloWorld.java
To run: java HelloWorld
public: can be accessed from
any other class in a Java
program
By convention, first letter of each word in a
class name is capitalized (no space or
underscore in between).
public: can be
invoked by any
caller
Name of the class being defined must
be the same as the name of the file
containing the class (.java extension)
case-sensitive
public class HelloWorld{
//Define the main method
public static void main( String[] args ) {
System.out.println(”Hello World!");
}
}
static: means method can be run
without first creating an object
from this class
Contains any
command-line
arguments passed
to the program
12
‘Hello, World!’ Example
VARIANTS
public class Hello{
public static void main(String[] args){
System.out.println("Hello,World!");
}
}
public class Hello2{
public static void main(String[] args){
String greetings = "Hello world!";
System.out.println(greetings);
}
}
public class Hello3{
private static String greetings = "Hello world!";
public static void main(String[] args){
System.out.println(greetings);
}
}
public class Hello4{
private String greetings = "Hello world!";
public Hello4(){
System.out.println(greetings);
}
public static void main(String[] args){
new Hello4();
}
13
}
‘Hello, World!’ Example
Static methods cannot use directly non-static fields and methods.
The main method is always declared static.
Constructors act like static methods, but are not explicitly declared static.
Constructors has no type,
Its name is the same as the
class name, and it is invoked by
using the keyword new.
public class Hello4{
private String greetings = "Hello world!";
public Hello4(){
System.out.println(greetings);
}
public static void main(String[] args){
new Hello4();
}
14
}
Hello World Example
• Things that might go wrong:
case sensitivity; files not found;
class not found…
• main() structure, necessary for
system/JVM
• System is class;
• out is static variable of type
PrintStream;
• println() is a method; also
System.err.print()
• note comment structure
• path and CLASSPATH need to
be set up for this to work (find
java and javac, and have . on
CLASSPATH )
15
Features Removed from C / C++
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
16
Features Removed from C/C++
• This section discusses features removed from C and C++ in the
evolution of Java.
• The first step was to eliminate redundancy from C and C++. In
many ways, the C language evolved into a collection of overlapping
features, providing too many ways to say the same thing, while in
many cases not providing the needed features. C++, in an attempt to
add "classes in C", merely added more redundancy while retaining
many of the inherent problems of C.
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
17
Features Removed from C/C++
1) No More Typedefs, Defines, or Preprocessor
• No preprocessor (operates on the source text, prior to any
parsing, by performing simple substitution of tokenized
character sequences according to user-defined rules.
(begins with ‘#’ as directives)
• No #define and related capabilities
• No typedef
• No header files, the Java language source files provide the
declarations of other classes and their methods
Problem with C/C++
• Too many #defines and typedefs results in every programmer inventing
another language
18
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
1) No More Typedefs, Defines, or Preprocessor
• Instead of #define, use constants
• Instead of typedef, declare classes
• Instead of header files, Java compiles class definitions into a binary form
• Java becomes remarkably context-free without these
• This will reduce the amount of context you need to understand before starting
with your coding.
19
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
2) No More Structures or Unions
• Java has no structures or unions as complex data types.
• You don't need structures and unions when you have classes;
you can achieve the same effect simply by declaring a class
with the appropriate instance variables.
The code fragment below declares
a class called Point.
class Point extends Object {
double x;
double y;
// methods to access the
// instance variables
}
class Rectangle extends Object {
Point lowerLeft;
Point upperRight;
// methods to access the
instance //variables
}
In C, these would be defined as structures, in Java, you simply declare classes
20
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
3) Originally No Enums (enum was introduced eventually)
• Java has no enum types.
• You can obtain something similar to enum by declaring a class whose only
raison d'etre is to hold constants.
You could use this feature something like this:
class Direction extends Object {
public static final int North = 1;
public static final int South = 2;
public static final int East = 3;
public static final int West = 4;
}
You can now refer to, say, the South constant using the notation Direction.South.
21
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
3) Originally No Enums (enum was introduced eventually)
You could use this feature something like this:
class Direction extends Object {
public static final int North = 1;
public static final int South = 2;
public static final int East = 3;
public static final int West = 4;
}
You can now refer to, say, the South constant using the notation Direction.South.
Using classes to contain constants in this way provides a major advantage over C's enum
types. In C (and C++), names defined in enums must be unique:
if you have an enum called HotColors containing names Red and Yellow, you can't use
those names in any other enum. You couldn't, for instance, define another Enum called
TrafficLightColors also containing Red and Yellow.
22
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
3) Originally No Enums (enum was introduced eventually)
class CompassRose extends Object {
public static final int North = 1;
public static final int NorthEast = 2;
public static final int East
= 3;
public static final int SouthEast = 4;
public static final int South = 5;
public static final int SouthWest = 6;
public static final int West
= 7;
public static final int NorthWest = 8;
}
There is no ambiguity because the name of the containing class acts as a qualifier
for the constants.
In the second example, you would use the notation CompassRose.NorthWest to
access the corresponding value. Java effectively provides you the concept of qualified
enums, all within the existing class mechanisms.
23
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
3) enum (J2SE 5.0) – it’s a full-fledged class!
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
...
PLUTO (1.27e+22, 1.137e6);
private final double mass; // in kg.
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
The enum type Planet contains a
constructor, and each enum constant is
declared with parameters to be passed to
the constructor when it is created.
public double mass() { return mass; }
public double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
public double surfaceGravity() {
return G * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}
24
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
Features Removed from C/C++
3) enum (J2SE 5.0) – it’s a full-fledged class!
Here is a sample program that takes your weight on earth (in any unit) and calculates and
prints your weight on all of the planets (in the same unit):
public static void main(String[] args) {
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n“, p, p.surfaceWeight(mass));
}
$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
...
25
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
Features Removed from C/C++
4) No More Functions
class Point extends Object {
double x;
double y;
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
• Anything you can do with a function you can
do just as well by defining a class and creating
methods for that class
If the x and y instance variables are private to
this class, the only means to access them is via
the public methods of the class.
26
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
5) No More Multiple Inheritance
• Multiple inheritance--and all the problems it generates--was discarded
from Java. The desirable features of multiple inheritance are provided by
interfaces
• An interface is not a definition of a class.
Rather, it's a definition of a set of methods that one or more classes will
implement.
• An interface is like an abstract base class in C++.
• An important issue of interfaces is that they declare only methods and
constants.
• Variables may not be defined in interfaces.
27
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
5) No More Multiple Inheritance
public interface OperateCar {
// constant declarations, if any
// method signatures
int turn(Direction direction, // An enum with values RIGHT, LEFT
double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
......
// more method signatures
}
28
http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html
Features Removed from C/C++
5) No More Multiple Inheritance
interface TargetPursuit{
public boolean targetDestroyed(int x, int y);
public int distance(int x, int y);
}
interface ObstacleAvoidance{
public boolean safeDistance();
public void findObstacles();
}
public class Robot{
protected void initialize(){
//Codes for initialize
}
protected void switchRole(){
//Codes for switchRole
}
protected void retreat(){
//Codes for retreat
}
}
public class Attacker extends Robot
implements TargetPursuit,
ObstacleAvoidance {
// Code here does something 29
}
Features Removed from C/C++
6) No More Goto Statements
• Java has no goto statement. Studies illustrated that goto is (mis)used
more often than not simply "because it's there".
• Eliminating goto led to a simplification of the language--there are no rules
about the effects of a goto into the middle of a for statement, for example.
• Studies on approximately 100,000 lines of C code determined that roughly
90% of the goto statements were used purely to obtain the effect of
breaking out of nested loops.
• As mentioned above, multi-level break and continue remove most of the
need for goto statements.
30
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
7) No More Operator Overloading
• There are no means provided by which programmers can overload the
standard arithmetic operators.
• Once again, the effects of operator overloading can be just as easily
achieved by declaring a class, appropriate instance variables, and
appropriate methods to manipulate those variables.
• Eliminating operator overloading leads to great simplification of code.
• There is one exception though, look at the String class:
String s1 = “meet me”;
String s2 = “ at sunset”;
String s = s1 + s2;
31
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
8) No More Automatic Coercions
• Java prohibits C and C++ style automatic coercions. If you wish to coerce
a data element of one type to a data type that would result in loss of
precision, you must do so explicitly by using a cast. Consider this code
fragment:
int myInt;
double myFloat = 3.14159;
• In Java, the assignment of
myFloat to myInt would result
in a compiler error
indicating a possible loss of
precision and that you must
use an explicit cast.
myInt = myFloat;
// This will only result to a warning in C++!
Thus, you should re-write the code fragments as:
int myInt;
double myFloat = 3.14159;
myInt = (int)myFloat;
32
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Features Removed from C/C++
9) No More Pointers
• Most studies agree that pointers are one of the primary features that
enable programmers to inject bugs into their code. Given that
structures are gone, and arrays and strings are objects, the need for
pointers to these constructs goes away. Thus, Java has no pointer data
types.
• Any task that would require arrays, structures, and pointers in C can be
more easily and reliably performed by declaring objects and arrays
of objects.
• Instead of complex pointer manipulation on array pointers, you access
arrays by their arithmetic indices.
• The Java run-time system checks all array indexing to ensure indices are
within the bounds of the array.
• You no longer have dangling pointers and trashing of memory because of
incorrect pointers, because there are no pointers in Java.
33
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
Applet
http://java.sun.com/docs/white/langenv/Simple.doc2.html#4076
34
‘Hello, World!’ applet
A web page will display an applet program in a
display area that is embedded between the other
contents on that page.
By default, this will appear as a blank
canvas onto which text, Swing
components, graphics and images can be
painted by the applet program.
import javax.swing.*;
import java.awt.*;
public class HelloWorldApplet extends JApplet
{
String message;
Serves like a constructor for
initializing variables and for adding
Swing components to the applet’s
interface.
public void init()
{
message = "Hello World";
}
The paint method is called spontaneously.
Applet inherits a paint() method from
JApplet class that can be used to paint
text, shapes and graphics into the applet’s
display area.
Knows how to
render content onto
the canvas.
public void paint(Graphics artist)
{
artist.drawString(message, 20, 30);
}
}
35
‘Hello, World!’ applet
To embed a Java applet in a web page, the
HTML code must specify the name of the applet
file and the size of the applet’s display area that
is to be allocated on the page.
The information is specified in the body of
the web page with attributes of the
HTML <applet> tag.
code attribute is assigned the name
of the compiled applet file
including its .class extension.
This pair of tags can surround a text message that
will only be displayed if the applet cannot be
executed.
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code = "HelloWorldApplet.class"
width = "300" height = "60">
You require a Java-enabled browser to view this applet.
</applet>
Default text
Embedding in a web page
</body>
</html>
Canvas size of
300x60 pixels in
which the applet
36
will run.
‘Hello, World!’ applet
Java SDK includes AppletViewer for testing
Compiled programs with the Java interpreter.
Both the HTML file and compiled applet
file should be saved together in a directory.
Testing with Applet Viewer
The applet can now be tested from a command prompt:
Appletviewer will
display the applet but
not other contents in a
web page.
Appletviewer HelloWorldApplet.html
Appletviewer will open a window that displays the HelloWorldApplet program:
37
Another form of Java comment
javadoc is an automatic system for generating program documentation directly
from comments embedded in Java programs.
javadoc comments start with the symbol /**
end with the symbol */, and can stretch over multiple lines.
These comments are automatically copied from Java source code into
documentation when the javadoc program is executed.
javadoc is described in the Java SDK documentation.
39
javadoc
JAVA DOCUMENTATION
/*
* @(#)Person.java 1.0 04/10/05
* Copyright 2005 Reyes Consulting, Inc.
*/
//import java.util.Date;
import java.util.*;
/**
* A class whose objects represent people.
* @author Napoleon R
* @version 1.0 04/10/05
* @see java.util.Date
* @since 1.2
*/
public class Person{
private String name;
private Date dob; //date of birth
private String address;
/**
* Constructs a Person object.
* @param aName the name of this person.
*/
public Person(String aName){
this.name = aName;
}
/**
* Constructs a Person object.
* @param aName the name of this person.
* @param aDob this person's date of birth
*/
public Person(String aName, Date aDob){
this.name = aName;
this.dob = aDob;
}
javadoc Person.java
See person.html40
javadoc
JAVA DOCUMENTATION
/**
* Returns a string that contains info. about this person
* @return a string that contains info. about this person.
*/
public String toString(){
return name + "(" + dob + ")";
}
/**
* prints info. about the person
*/
public void printinfo(){
System.out.println(name);
System.out.println(address);
System.out.println(dob);
}
/**
* sets address of person
*/
public void setAddress(String a) {
address = a;
}
/**
* sets date of birth of person
*/
public void setDateOfBirth(int year, int month, int day){
// Get object of type calendar and set it to the given date
Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0, 0);
// Get a date object and assign it to dateOfBirth
dob = c.getTime();
}
static public void main(String[] args) {
Person p = new Person("Napoleon");
p.setAddress("Albany");
p.setDateOfBirth(1900, 4, 25);
p.printinfo();
}
}
//end of class Person
41
See person.html
Java Primitive Data Types
//
// Primitive Types Example Program
//
public class Types{
public static void main( String args[] ) {
boolean b = true;
// try out various primitive
byte eight = 8;
// type declarations
short little = 16384;
int i, j, k;
long l = 42L;
float f;
double d;
double e = 2.71828182846;
char ch ='a';
i = 12; j = 032; k = 0xFF; // try out some simple
f = 3.141592654F;
// assignments
d = (double) f;
i = eight;
// try vagaries of string concatenation
System.out.println("d is: " + d );
System.out.println(i + f + d + j + k + " " + b );
System.out.println(eight + little + " using arithmetic");
System.out.println(eight + " " + little + " using arithmetic");
•
•
•
•
•
boolean
byte, short, int, long
float, double - IEEE 754
char
reference type is used for objects
• Results:
> java Types
d is: 3.1415927410125732
295.2831857204437 true
16392 using arithmetic
8 16384 using arithmetic
>
}
}
42
Java Literals
• literals int unless L or l suffix used
• octal using leading 0 and hex using leading 0x
• real numbers are double unless F or f suffix (opposite
to int)
• There is a definite memory model for these, sizes of
primitives fixed - see table
• Strings and arrays are special reference types
The range of values are given in the next slide.
43
Java Data Types Memory Usage
Type
Description
Default Size(bits) Min/Max
boolean
true/false
false
1
Not applicable
char
Unicode character
\u0000
16
\u0000
\uFFFF
byte
Signed integer
0
8
-128
127
short
Signed integer
0
16
-32768
32767
int
Signed integer
0
32
-2147483648
2147483647
long
Signed integer
0
64
-9223372036854775808
9223372036854775807
float
IEEE 754 Floating
point
0.0
32
+/- 1.40239846E-45
+/- 3.40282347E+38
double
IEEE 754 floating
point
0.0
64
+/- 4.94065645841246544E-324
+/- 1.79769313486231570E-308
44
Coding Conventions
• http://java.sun.com/docs/codeconv/index.html
Updates
• http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html
API
http://java.sun.com/j2se/1.5.0/docs/api/index.html
45
Interactive String Input (old approach)
Java manages all input through stream objects, which throw exceptions
that are meant to be caught.
To input a string, you need these pieces of Java code:
This code creates an object,
named in, that can execute its
readLine() method to input
strings interactively.
Import java.io.*;
BufferedReader in;
throws IOException
in = new BufferedReader(new InputStreamReader(System.in));
To read one string per line of
input, you can use:
in.readLine()
Read text from a characterinput stream, buffering
characters for efficient
reading of characters, arrays,
and lines
Interactive Hello
Reads bytes and translates
them into characters
according to a specified
character encoding
import java.io.*;
class Hello{
public static void main(String[] args) throws IOException{
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = in.readLine();
System.out.println("Hello, " + name);
}
46
}
Interactive String Input (since v.5)
To input a string, you need this:
import java.util.Scanner;
To read one string per line of
input, you can use:
nextLine()
Interactive Hello
import java.util.Scanner;
class Hello2{
public static void main(String[] args) {
Read text from a characterinput stream, buffering
characters for efficient
reading of characters, arrays,
and lines
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.println("Hello, " + name);
}
}
47
Interactive Numeric Input (since v.5)
To input a number, you this:
import java.util.Scanner;
Interactive Addition
import java.util.Scanner;
To read a number, you can
use one of the following:
nextInt(),
nextFloat(),
nextDouble(),
nextByte(), etc…
class Addition2{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, sum;
System.out.print("Enter first integer: ");
num1 = input.nextInt();
System.out.print("Enter second integer: ");
num2 = input.nextInt();
sum = num1 + num2;
System.out.printf("Sum is %d\n", sum);
}
}
48
Classes and Objects
Class Point
public class Point{
private int x, y;
public Point(int x, int y){
This has no main()
this.x = x;
method and so it cannot
this.y = y;
be executed as a Java
}
program.
public boolean equals(Point p){
return (x == p.x && y == p.y);
}
49
public int getX(){
return x;
Whenever an object of this
}
class is expected to return a
public int getY(){
String, the compiler
return y;
automatically invokes the
}
toString() method.
public String toString(){
return new String("(" + x + ", " + y + ")");
}
}
Classes and Objects
TestPoint
public class TestPoint{
public static void main(String args[]){
Point p = new Point(2, -3);
System.out.println("p: " + p);
System.out.println("p.getX(): " + p.getX());
System.out.println("p.getY(): " + p.getY());
Point q = new Point(7,4);
System.out.println("q: " + q);
System.out.println("q.equals(p): " + q.equals(p)); 50
System.out.println("q.equals(q): " + q.equals(q));
}
}
For as long as the
resulting Point.class
file is in the same
folder as our
TestPoint.java file, we
can compile and run
our test program.
3 main kinds of declarations in a Java class
Syntax
Fields
Modifiers
type name;
Constructors
Modifiers class_name (parameters) {
statements
}
Methods
Modifers return_type name (parameters) clause {
statements
}
51
Class Modifiers
Modifier
Meaning
abstract
The class cannot be instantiated
final
The class cannot be extended
public
Its members can be accessed
from any other class.
52
Field Modifiers
Modifier
Meaning
final
It must be initialized and cannot be changed
private
It is accessible only from within its own class
protected
It is accessible only from within its own class and
its extensions.
public
It is accessible from all classes
static
The same storage is used for all instances of the
class.
transient
It is not part of the persistent state of an object
volatile
It may be modified by asynchronous threads
Examples:
private double m;
private transient String middleName;
53
Constructor Modifiers
Modifier
Meaning
private
It is accessible only from within its own class.
protected
It is accessible only from within its own class and
its extensions.
public
It is accessible only all classes.
54
Method Modifiers
Modifier
Meaning
final
It cannot be overridden in class extensions
native
Its body is implemented in another programming
language.
private
It is accessible only from within its own class.
protected
It is accessible only from within its own class and
its extensions.
static
It has no implicit argument.
synchronized
It must be locked before it can be invoked by a
thread.
volatile
It may be modified by asynchronous threads.
55
Local Variable Modifier
Modifier
Meaning
final
It must be initialized and cannot be changed.
56
Access Modifiers
The three access modifiers, public, protected, and private, are used
to specify where the declared entity (class, field, constructor, or
method) can be used.
If none of these is specified, then the entity has package access,
which means that it can be accessed from any class in the same
package.
57
Access Modifiers
The modifier final has three different meanings, depending upon
which kind of entity it modifies.
If it modifies a class, it means that the class cannot have subclasses.
If it modifies a field or a local variable, it means that the variable
must be initialized and cannot be changed (i.e. constant).
If it modifies a method, it means that the method cannot be
overridden in any subclass.
public final class MyFinalClass {...}
public final double radius;
public final double xpos;
public class MyClass {
public final void myFinalMethod() {...}
}
58
Access Modifiers
The modifier static is used to specify that a method is a class method.
Without it, the method is an instance method.
An instance method is a method that can be invoked only when bound
to an object of the class. That object is called an implicit argument of
the method invocation.
For example,
p.getX(); //getX() is bound to object p, so p is its implicit argument.
A class method (or static method) is a method that is invoked without
being bound to any specific object of the class.
Note that every program’s main() method is a class method.
See next slide for an example...
59
Classes and Objects
Class Point
public class Point{
private int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
...
public static double distanceBetween(Point p1, Point p2){
double dx = p2.x – p1.x;
double dy = p2.y – p1.y; 60
return Math.sqrt(dx*dx + dy*dy);
}
}
In a separate program,
...
//sample function call
System.out.println(“distance = “ + Point.distanceBetween(p, q));
// Structure of Java programs, Example
// package XYZ;
// if missing, file is part of anonymous package
import java.lang.*; // imports
public class Structure{ // at most one public class per file
// if class is public, then must match filename
// member variables and methods follow in any order
public static int instancecount = 0; // shared by all instances
private int serialnumber;
// belongs to an instance object
Structure(){
System.out.println(" A Structure has been constructed ");
instancecount++;
serialnumber = instancecount; }
public int getserialnumber(){ // return serial number of instance
return serialnumber; }
public int getinstancecount(){ // return number of objects
return instancecount;
// instantiated so far }
public static void main(String args[]){ // main must match this pattern if present
System.out.println("arguments are:");
for(int i=0;i<args.length;i++){
System.out.println(args[i]); // NB, no argc nor C-like argv[0] }
library(); // accessible since it is a class method
Structure s = new Structure();
s.test(); // invoke instance's test method
System.out.println( "Serial No is: " + s.getserialnumber() );
s = new Structure(); // create a new instance, discard old one
System.out.println("instancecount is " + instancecount);
// access direct since main is part of the class
ancillary.help(); }
public void test(){ // an instance method
System.out.println("test method in class Structure"); }
public static void library(){
System.out.println("Callable without an instantiation of class");
// will need to be called as Structure.library() outside this class }
}
class ancillary{
static void help(){
System.out.println("No help information available"); }
}
• Java Source File Structure:
– package statement (optional, defaults
to anonymous package)
– import statement(s) (optional)
– class definition(s)
– at most one public class per file,
whose name must match filename
– class(es) contain member variables
and methods in any order
• Results:
> java Structure
arguments are:
Callable without an instantiation of class
A Structure has been constructed
test method in class Structure
Serial No is: 1
A Structure has been constructed
instancecount is 2
No help information available
>
61
Objects and References to Them
Lifetime of an object
public class TestPoint2{
public static void main(String args[]){
Point p = null, q = null;
p = new Point(2, -3);
//p gets memory from heap
q = p; //both p and q points to the same memory location
p = new Point(7,4); //p gets a new memory location again
q = p; //the previous memory location pointed by q is garbage-collected
p = null; //q still points to the memory alloted
for p earlier
62
q = null; //the object pointed by q earlier will be garbage collected.
}
}
The life of an object begins when it is created by a constructor, and it continues as
long as there is at least one reference to it. When its last reference has been
reassigned, then the object dies.