A Crash Course on Java

advertisement
A Crash Course on Java
Java - A Brief Introduction
http://docs.oracle.com/javase/tutorial/j
ava/index.html
3/23/2016
1
History of Java
• Sun Microsystems in 1991 funded an internal
corporate research project “Green”
• James Gosling was the person in charge
• Green resulted in a C++ based language called
Oak, later changed to Java
• Oak was designed to be used to program
consumer-electronic devices
• Oak ran into difficulties due to market
• WWW explored in 1993 and Java’s potential to
produce dynamic content was recognized
3/23/2016
2
About the Java Technology
• The Java Programming Language
• The Java Platform
3/23/2016
3
Java Programming Language
• All source code is written in text files with
.java extension.
• Source files are compiled into .class files by
javac compiler.
• A .class file contains bytecodes — the
machine language of the Java VM.
• java launcher runs application on Java VM.
3/23/2016
4
Compile once, run everywhere
• JVM is available on different
operating systems
• The same .class files are
capable of running on
Microsoft Windows, the Solaris
TM Operating System (Solaris
OS), Linux, or Mac OS.
• Some virtual machines, (Java
HotSpot VM), at run time
– find performance
bottlenecks
– recompile (to native code)
frequently used sections of
code
3/23/2016
5
The Java Platform
• A platform is the hardware or software
environment in which a program runs.
– Microsoft Windows, Linux, Solaris OS, and Mac OS.
• Most platforms can be described as a
combination of the operating system and
underlying hardware.
• Java platform is a software-only platform that
runs on top of other hardware-based platforms.
3/23/2016
6
Java platform consists of
• The Java Virtual Machine
• The Java Application Programming Interface
(API)
3/23/2016
7
Java Class Libraries
• All Java programs consist of classes
• Classes consist of data members and
function members (methods)
• Java programmers can write their own
classes
• They can also use existing classes in Java
class libraries (Java API – Application
Programming Interfaces)
3/23/2016
8
Set Up Java Development
Environment (JDK)
• Download JDK installer from
http://www.oracle.com/technetwork/java/javase/d
ownloads/index.html
(Choose the basic JDK to download)
• Install the JDK
• Set up the platform environment (PATH)
http://docs.oracle.com/javase/tutorial/essential/e
nvironment/index.html
3/23/2016
9
Steps to create Java Program
• Creating a program using any editor and save the file as
.java file such as test.java
• Compile Java program into bytecodes
%javac test.java
• Initiate JVM to execute program
%java test
– Load a program into memory
– Bytecode verification
– Execution
3/23/2016
10
Where to find help
• Getting started
http://docs.oracle.com/javase/tutorial/getStarted/i
ndex.html
• For tutorial
http://docs.oracle.com/javase/tutorial/
• For documentation
http://docs.oracle.com/javase/7/docs/
• For API documents
http://docs.oracle.com/javase/7/docs/api/
3/23/2016
11
The "Hello World!" Application
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
3/23/2016
12
Java Commenting Styles
• /* comments */ or // comments
• /** documentation */
– The javadoc tool uses doc comments
when preparing automatically generated
documentation.
http://www.oracle.com/technetwork/java/ja
vase/documentation/index-jsp135444.html
3/23/2016
13
Java Language Basics
• Variables
– Local Variables
– Parameters
– Instance Variables (Non-Static Fields)
– Class Variables (Static Fields)
3/23/2016
14
Java Language Basics
• Naming
– Variable names are case-sensitive.
– Always begin your variable names with a letter.
– Use full words instead of cryptic abbreviations.
– If the name you choose consists of only one word, spell that word in all
lowercase letters. If it consists of more than one word, capitalize the first
letter of each subsequent word.
gearRatio and currentGear
– If your variable stores a constant value
static int NUM_GEARS = 6
3/23/2016
15
Java Language Basics
• Array
int[] anArray; // declares an array of integers
anArray = new int[10]; // create an array of integers
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
3/23/2016
16
Classes declarations include:
• Modifiers such as public, private, protected.
• The class name, with the initial letter
capitalized by convention.
• The first (or only) word in a method name
should be a verb.
• The class body, surrounded by braces, { }.
3/23/2016
17
• The name of the class's parent (superclass)
preceded by the keyword extends. A class
can only extend (subclass) one parent.
• A list of interfaces implemented by the class
preceded by the keyword implements. A
class can implement more than one
interface.
3/23/2016
18
public class Bicycle {
private int cadence;
private int gear;
private int speed;
public Bicycle(int startCadence,
int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public int getCadence() {
return cadence;
}
public void setCadence(int newValue)
{
cadence = newValue;
}
3/23/2016
19
public int getGear() {
return gear;
}
public void setGear(int newValue) {
gear = newValue;
}
public int getSpeed() {
return speed;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
3/23/2016
20
public class Point {
private int x = 0;
private int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
Point originOne = new Point(23, 94);
3/23/2016
21
public class Rectangle {
private int width = 0;
private int height = 0;
private Point origin;
public Rectangle() {
// four constructors
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
public void move(int x, int y) { // moving the rectangle
origin.x = x;
origin.y = y;
}
public int getArea() {
//computing the area of the rectangle
return width * height;
3/23/2016 }
22
Understanding Instance and Class Members
• static keyword is used to create fields and
methods that belong to the class
public class Bicycle{
private int cadence;
private int gear;
public int speed;
public static int numberOfBicycles = 0;
......
}
3/23/2016
23
• Class variables/methods can be referred
to by using class name directly
Bicycle.numberOfBicycles
• Instance variables/methods have to be
referred to using object name
Bicycle b1;
b1.speed
3/23/2016
24
Things to be aware of
• Instance methods can access instance variables
and instance methods directly.
• Instance methods can access class variables
and class methods directly.
• Class methods can access class variables and
class methods directly.
• Class methods cannot access instance
variables or instance methods directly—they
must use an object reference.
• Class methods cannot use this keyword as
there is no instance for this to refer to.
3/23/2016
25
Constants
• The final modifier declares a variable not modifiable
final double PI;
• A final variable must be initialized
• The static modifier, in combination with the final modifier,
can be used to define constants.
static final double PI = 3.141592653589793;
• Constants cannot be reassigned, and it is a compile-time
error if your program tries to do so.
3/23/2016
26
Initializing Fields
• Provide an initial value for a field in its
declaration if the value is available or simple:
public class BedAndBreakfast {
public static int capacity = 10; //initialize to 10
private boolean full = false; //initialize to false
}
• If initialization requires some logic:
– Class variables can be initialized using static
initializer blocks or private static method.
– Instance variables can be initialized in
constructors, initializer blocks and final methods.
3/23/2016
27
Initializing instance variables
• constructors
• Initializer blocks (Java compiler copies initializer blocks into every
constructor.)
{
// code to initialize instance variables
}
• final methods
class Whatever {
private varType myVar = initializeInstanceVariable();
protected final varType initializeInstanceVariable() {
//initialization code goes here
}
}
3/23/2016
28
Initializing class variables
• Static initializer blocks
static {
// code to initialize class variables
}
• Private static methods
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
//initialization code goes here
}
}
3/23/2016
29
•
Nested Classes
Define a class within another class.
class OuterClass {
...
class NestedClass {
...
}
}
•
•
A nested class is a member of its enclosing class and has access to all other members of
the enclosing class.
Nested classes are divided into two categories: static and non-static.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
•
A nested class can be declared private, public, protected, or package private.
3/23/2016
30
Why Use Nested Classes?
• It is a way of logically grouping classes that
are only used in one place.
• It increases encapsulation.
• Nested classes can lead to more readable
and maintainable code.
3/23/2016
31
Static Nested Classes
• A static nested class is associated with its outer class.
• A static nested class cannot refer directly to instance
variables or methods defined in its enclosing class — it can
use them only through an object reference.
• A static nested class interacts with the instance members of
its outer class (and other classes) just like any other top-level
class.
• Static nested classes are accessed using the enclosing class
name:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
3/23/2016
32
Inner Classes
• An inner class is associated with an instance
of its enclosing class and has direct access to
all its methods and fields.
• Because an inner class is associated with an
instance, it cannot define any static members
itself.
• Objects that are instances of an inner class
exist within an instance of the outer class.
3/23/2016
33
• To instantiate an inner class, you must first
instantiate the outer class.
OuterClass outerObject = new OuterClass();
• Then, create the inner object within the outer
object with this syntax:
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();
3/23/2016
34
public class StackOfInts {
private int[] stack;
private int next = 0; // index of last item in stack + 1
public StackOfInts(int size) {//create an array to hold the stack
stack = new int[size];
}
public void push(int on) {
if (next < stack.length)
stack[next++] = on;
}
public boolean isEmpty() {
return (next == 0);
}
public int pop(){
if (!isEmpty())
return stack[--next]; // top item on stack
else
return 0;
}
public int getStackSize() {
return next;
}
3/23/2016
35
private class StepThrough {// beginning of StepThrough inner class
// start stepping through at i=0
private int i = 0;
// increment index
public void increment() {
if ( i < stack.length) i++;
}
// retrieve current element
public int current() {
return stack[i];
}
// last element on stack?
public boolean isLast(){
if (i == getStackSize() - 1) return true;
else return false;
}
} // end of StepThrough inner class
public StepThrough stepThrough() {
return new StepThrough();
}
3/23/2016
36
public static void main(String[] args) {
// instantiate outer class as "stackOne"
StackOfInts stackOne = new StackOfInts(15);
// populate stackOne
for (int j = 0 ; j < 15 ; j++) {
stackOne.push(2*j);
}
// instantiate inner class as "iterator"
StepThrough iterator = stackOne.stepThrough();
// print out stackOne[i], one per line
while(!iterator.isLast()) {
System.out.print(iterator.current() + " ");
iterator.increment();
}
System.out.println();
} // end of main method
} // end of StackOfInts
3/23/2016
37
• There are two additional special kinds of inner
classes:
– local classes
– anonymous classes (also called anonymous inner
classes).
• You can declare an inner class within the
body of a method. Such a class is known as a
local inner class.
• You can also declare an inner class within the
body of a method without naming it. These
classes are known as anonymous inner
classes.
3/23/2016
38
public class LocalInnerClass {
private static Test monitor = new Test();
private int count = 0;
Counter getCounter(final String name) { // A local inner class:
class LocalCounter implements Counter{
public LocalCounter() { // Local inner class can have a
//constructor
System.out.println("LocalCounter()"); }
public int next() {
System.out.print(name); // Access local final
return count++; }
}
return new LocalCounter();
} // end of getCounter
3/23/2016
39
// The same thing with an anonymous inner class:
Counter getCounter2(final String name) {
return new Counter()
{ // Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{ System.out.println("Counter()"); }
public int next() {
System.out.print(name); // Access local final
return count++; }
};
} // end of getCounter2
3/23/2016
40
Numbers Classes
• When working with numbers, most of the time you use
the primitive types in your code.
int i = 500;
float gpa = 3.65;
• Java platform provides wrapper classes for each of the
primitive data types. These classes "wrap" the primitive
in an object.
Integer x, y;
x = 12;
y = 15;
System.out.println(x+y);
3/23/2016
41
Numeric wrapper classes are subclasses of
the abstract class Number:
3/23/2016
42
Reasons to use a Number object
rather than a primitive:
•
•
•
As an argument of a method that expects an
object.
To use constants defined by the class, such as
MIN_VALUE and MAX_VALUE, that provide
the upper and lower bounds of the data type.
To use class methods
–
–
–
3/23/2016
converting values to and from other primitive types,
converting to and from strings, and
converting between number systems (decimal,
octal, hexadecimal, binary).
43
Characters Classes
•
Most of the time, you will use the primitive char type.
char ch = 'a';
char uniChar = '\u039A'; // Unicode for uppercase Greek omega character
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; // an array of chars
•
Java provides a wrapper class that "wraps" the char in a Character object.
•
The Java compiler will also automatically converts the char to a Character
(autoboxing) or unboxing, if the conversion goes the other way.
Character ch = new Character('a');
Character ch = 'a';
Character test(Character c) {...}
char c = test('x');
3/23/2016
44
Strings classes
•
Creating Strings
String greeting = "Hello world!";
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
•
Converting Strings to Numbers
String s1;
String s2;
int i = (Integer.valueOf(s1) ).intValue(); ;
double d = (Float.valueOf(s2) ).floatValue(); ;
•
Converting Numbers to Strings
int i;
double d;
String s1 = Integer.toString(i);
String s2 = Double.toString(d);
3/23/2016
45
Numbers and String Classes
• Self reading
http://docs.oracle.com/javase/tutorial/java/
data/index.html
3/23/2016
46
Using the this Keyword
• Within an instance method or a constructor, this is a
reference to the current object — the object whose
method or constructor is being called.
• You can refer to any member of the current object from
within an instance method or a constructor by using this.
3/23/2016
47
Using this with a Field
• The most common reason for using the
this keyword is because a field is
shadowed by a method or constructor
parameter.
public class Point {
private int x = 0;
private int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
3/23/2016
public class Point {
private int x = 0;
private int y = 0;
//constructor
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
48
Explicit constructor invocation
• use this keyword to call another constructor
within a constructor
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
3/23/2016
}
49
Controlling Access to Class and
Members of a Class
• At the class level:
– public: visible to all classes everywhere
– package-private (no explicit modifier): visible
only within its own package
• At the member level:
– public:
– package-private (no explicit modifier)
– private: visible in its own class
– protected: visible within its own package and by
a subclass of its class in another package.
3/23/2016
50
public class LocalInnerClass {
private static Test monitor = new Test();
private int count = 0;
Counter getCounter(final String name) { // A local inner class:
class LocalCounter implements Counter{
public LocalCounter() { // Local inner class can have a
//constructor
System.out.println("LocalCounter()"); }
public int next() {
System.out.print(name); // Access local final
return count++; }
}
return new LocalCounter();
} // end of getCounter
3/23/2016
51
// The same thing with an anonymous inner class:
Counter getCounter2(final String name) {
return new Counter()
{ // Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{ System.out.println("Counter()"); }
public int next() {
System.out.print(name); // Access local final
return count++; }
};
} // end of getCounter2
3/23/2016
52
Class Member Visibility
Member
Modifier
3/23/2016
Alpha
(class)
Beta
(package)
AlphaSub
(subclass)
Gamma
(world)
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
53
Tips on choosing access level
• Use the most restrictive access level that
makes sense for a particular member.
• Use private unless you have a good
reason not to.
• Avoid public fields except for constants.
3/23/2016
54
Packages
•
To make types easier to find and use, to avoid naming conflicts, and to
control access, programmers bundle groups of related types into packages.
•
A package is a grouping of related types (class, interface, enumerations,
annotation) providing access protection and name space management.
java.lang
java.io
•
To create a package, put a package statement with that name at the top of
every source file that you want to include in the package.
package graphics;
class Window{
}
3/23/2016
55
//in the Draggable.java file
package graphics;
public interface Draggable { . . . }
//in the Graphic.java file
package graphics;
public abstract class Graphic { . . . }
//in the Circle.java file
package graphics;
public class Circle extends Graphic implements Draggable { . . . }
//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic implements Draggable { . . . }
3/23/2016
56
Note
• If you put multiple classes in a single source file,
only one can be public, and it must have the
same name as the source file.
• You can include non-public types in the same
file as a public class, but only the public type will
be accessible from outside of the package.
• All the top-level (class), non-public types will be
package private.
3/23/2016
57
Naming Conventions
• Package names are written in all lowercase
• Some companies use their reversed Internet
domain name to begin their package names
package com.example.orion;
is used for a package named orion created
by programmers at example.com.
3/23/2016
58
Ways to use a public package
class from outside its package
• Refer to the member by its fully qualified name
graphics.Rectangle myRect = new graphics.Rectangle();
• Import the package member
import graphics.Rectangle;
Rectangle myRectangle = new Rectangle();
• Import the member's entire package
import graphics.*;
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();
3/23/2016
59
For convenience, Java compiler
imports the following three
packages for all source files:
• the package with no name
• the java.lang package
• the current package (the package for the
current file).
3/23/2016
60
Hierarchies of Packages
• Not hierarchical
– the Java API includes a
java.awt
java.awt.color
java.awt.font
and many other packages with
java.awt.xxx
– The prefix java.awt (the Java Abstract Window Toolkit)
is used for a number of related packages
to make the relationship evident, but not to show
inclusion.
3/23/2016
61
• Importing java.awt.* imports
– all of the types in the java.awt package,
– but it does not import java.awt.color, java.awt.font, or
any other java.awt.xxx packages.
• If you plan to use the types in java.awt.color as
well as those in java.awt, you must import both
packages:
import java.awt.*;
import java.awt.color.*;
3/23/2016
62
Managing Source and Class Files
• Put the source code in a text file whose name is the
simple name of the public class with extension .java.
// in the Rectangle.java file
package graphics;
public class Rectangle() { . . . }
• Then, put the source file in a directory whose name
reflects the name of the package to which the type
belongs:
.....\graphics\Rectangle.java
3/23/2016
63
.class file directory
• You can arrange your source and class
directories separately, as:
<path_one>\sources\com\example\graphics\Rectangle.java
<path_one>\classes\com\example\graphics\Rectangle.class
• The full path to the classes directory,
defined in CLASSPATH, should be set to
<path_one>\classes
3/23/2016
64
Compilation
•
When you compile a source file, the compiler creates a different output file
for each type defined in it.
•
The base name of the output file is the name of the type, and its extension
is .class.
•
For example:
// in the Rectangle.java file
package com.example.graphics;
public class Rectangle{ . . . }
class Helper{ . . . }
then the compiled files will be located at:
<class path>\com\example\graphics\Rectangle.class
<class path>\com\example\graphics\Helper.class
3/23/2016
65
More About Java
http://docs.oracle.com/javase/tutorial/java/IandI/index.html
and
Java How to Program
By
Deitel & Deitel
3/23/2016
66
Object class
• All classes in Java inherit directly or
indirectly from the Object class (java.lang)
• It has 11 methods that are inherited by all
other classes.
3/23/2016
67
clone method
• protected method
• Default implementation is to perform a
shallow copy.
• A typical overridden clone method will
perform a deep copy.
3/23/2016
68
Two object references A, B
3/23/2016
69
Shallow copy process
3/23/2016
70
Deep copy
3/23/2016
71
Lazy copy
• A lazy copy is a combination of both strategies
above.
• When initially copying an object, a (fast) shallow
copy is used.
• A counter is also used to track how many
objects share the data.
• When the program wants to modify an object, it
can determine if the data is shared (by
examining the counter) and can do a deep copy
if necessary.
3/23/2016
72
euqals method
• protected method
• Return a boolean value
• Default implementation is to determine
whether two references refer to the same
object.
3/23/2016
73
finalize method
•
•
•
•
protected method
Take no parameter and return void
Default implementation is to do nothing
Called by the garbage collector to perform
termination house keeping on an object
before the object is reclaimed by garbage
collector
3/23/2016
74
getClass method
• public final method
• Returns an object of class Class (java.lang)
• The object of Class contains the information
about an object (its class name, etc)
3/23/2016
75
public class Base {
}
public class Derived extends Base {
}
// Test the getClass() method for the above classes.
Base base = new Base();
Base derived = new Derived();
System.out.println("Class for base object = " +
base.getClass().getName());
System.out.println("Class for derived object = " +
derived.getClass().getName());
OUTPUT:
Class for base object = Base
Class for derived object = Derived
3/23/2016
76
Object API
• http://docs.oracle.com/javase/1.5.0/docs/a
pi/java/lang/Object.html
• http://docs.oracle.com/javase/tutorial/java/I
andI/objectclass.html
•
3/23/2016
77
Abstract class & abstract method
• An abstract class is a class that is declared
abstract—it may or may not include abstract
methods.
• Abstract classes cannot be instantiated, but they
can be subclassed.
• An abstract method is a method that is declared
without an implementation:
abstract void moveTo(double deltaX, double deltaY);
3/23/2016
78
Abstract class usages
• An abstract class declares common attributes
and behaviors of the various classes in a class
hierarchy.
• It typically contains one or more abstract
methods that sub class must override if the sub
classes are to be concrete.
• The instance variables and concrete methods of
an abstract class are subject to the normal rules
of inheritance.
3/23/2016
79
Interfaces
• To disparate groups of programmers to
agree to a "contract" that spells out how
their software interacts.
• Each group should be able to write their
code without any knowledge of how the
other group's code is written.
• Generally speaking, interfaces are such
contracts.
3/23/2016
80
• An interface is typically used when
unrelated classes need to share common
methods and constants.
• This allows objects of unrelated classes to
be processed polymorphically:
i.e., objects of classes that implement the
same interface can respond to the same
method calls.
3/23/2016
81
Interfaces in Java
• An interface is a reference type that can
contain only constants, method signatures,
and nested types. There are no method
bodies.
• Interfaces cannot be instantiated—they
can only be implemented by classes or
extended by other interfaces.
3/23/2016
82
Defining an Interface
public interface GroupedInterface extends
Interface1, Interface2, Interface3 {
// constant declarations
double E = 2.718282;
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
3/23/2016
83
• A method declaration within an interface is
followed by a semicolon.
• All methods declared in an interface are
implicitly public.
• An interface can contain constant
declarations and they are implicitly public,
static, and final.
3/23/2016
84
To use an interface
• A concrete class must specify that it
implements an interface
• When an concrete class implements an
interface, it must provide a method body
for every method declared in the interface.
3/23/2016
85
Implementing an Interface
• To declare a class that implements an interface, you
include an “implements” clause in the class declaration.
• By convention, the implements clause follows the
extends clause, if there is one.
• A class can implement more than one interface.
• When a class implements an interface, it must provide a
method body for every method declared in the interface.
3/23/2016
86
public interface OperateCar {
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
int turn(Direction direction, double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
}
public class OperateBMW760i implements OperateCar {
int signalTurn(Direction direction, boolean signalOn) {
//code to implement this function for BMW
}
int getRadarFront(double distanceToCar, double speedOfCar){
//code to implement this function for BMW
}
int getRadarRear(double distanceToCar, double speedOfCar){
//code to implement this function for BMW
}
int turn(Direction direction, double radius, double startSpeed, double endSpeed){
//code to implement this function for BMW
}
int changeLanes(Direction direction, double startSpeed, double endSpeed){
//code to implement this function for BMW
}
}
3/23/2016
87
Extending Interfaces
• Consider an interface that you have developed called DoIt:
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
}
• Suppose that, at a later time, you want to add a third method to DoIt,
– You can either
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x, String s);
}
– Create a DoItPlus interface that extends DoIt:
public interface DoItPlus extends DoIt {
boolean didItWork(int i, double x, String s);
3/23/2016 }
88
Using an Interface as a Type
• When you define a new interface, you are
defining a new reference data type.
• You can use interface names anywhere
you can use any other data type name.
• If you define a reference variable whose
type is an interface, any object you assign
to it must be an instance of a class that
implements the interface.
3/23/2016
89
Interfaces & Multiple Inheritance
• The Java programming language does not
permit multiple inheritance, but interfaces
provide an alternative.
• In Java, a class can inherit from only one
class but it can implement more than one
interface.
3/23/2016
90
Summary of Interfaces
• An interface defines a protocol of communication
between two types of objects.
• An interface declaration contains signatures, but
no implementations, for a set of methods, and
might also contain constant definitions.
• A class that implements an interface must
implement all the methods declared in the
interface.
• An interface name can be used anywhere a type
can be used.
3/23/2016
91
Abstract Class vs. Interface
Both of them:
•
•
•
•
•
are the ways to implement Polymorphism.
can not be instantiated.
can only be used as super classes.
need to declare in same name file with .java extension.
Abstract methods and methods in an interface can only
be signatures without any state or implementation.
• Abstract methods and methods in an interface need to
be implemented in concrete classes.
3/23/2016
92
Abstract Class vs. Interface
But:
• Abstract classes serve states and or
implementations while interfaces can’t.
• Interfaces only serve method signatures and
constants.
• Abstract classes will be extended but Interfaces
will be implemented.
• Unlike classes all the interfaces’ methods must
be public.
3/23/2016
93
Applications:
•
•
•
•
•
•
•
•
•
An interface is just a pattern while an abstract class is a real class with all the
abilities.
Interfaces and Abstract classes both share a common design.
Interfaces are useful when you need to create disparate and unrelated objects with
same behaviors.
Abstract classes are useful when you need to create closely related objects with
common implementations.
Abstract classes help you to have a more extensible and reusable code.
Interfaces help you to have more structured code.
When you want a super class without any default implementation interfaces are what
you want.
In Java, classes are not allowed to inherit from more than one class but it’s possible
by interfaces.
Declaring constants in interfaces keeps your code clear and easy to maintain.
3/23/2016
94
《interface》
Payable
Invoice
Employee
HourlyEmployee
Click here to see the source code
3/23/2016
SalariedEmployee
Commission
Employee
BonusPlusCommission
Employee
95
Download