Programming Language 2: Course 7
Programming Language 2: Course 7
language 2
Course 7
Loredana STANCIU
[email protected]
Room B612A
Abstract Methods and
Classes
An abstract class:
a class that is declared abstract
cannot be instantiated, but they can be inherited
An abstract method — a method that is declared
without an implementation
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself
must be declared abstract
Abstract Methods and
Classes
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}
The subclass has to provide implementations for all of
the abstract methods — abstract
Abstract Methods and
Classes
Abstract Methods and
Classes
Graphic objects:
states (for example: position, orientation, line color, fill
color)
behaviors (for example: moveTo, rotate, resize, draw)
Abstract Methods and
Classes
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY)
{ ... }
abstract void draw();
abstract void resize();
}
Abstract Methods and
Classes
class Circle extends GraphicObject {
void draw() { ... }
void resize() { ... }
}
class Rectangle extends GraphicObject {
void draw() { ... }
void resize() { ... }
}
Abstract Methods and
Classes
Interfaces
interface Writer{
public void write();}
Use type casting to call methods that are not defined in the
interface
((SwimProfessor)sp).dive();
((SwimProfessor)sp).swim();
Rewriting Interfaces
An initial version
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s); }
Want to revise it
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x,
String s); }
Rewriting Interfaces
All classes that implement the old DoIt interface will break
because they don't implement the interface anymore
Try to anticipate all uses for your interface and to specify it
completely from the beginning
protected int p;
Creating and Using
Packages
Creating a Package
Important
If you put multiple types in a single source file, only one can
be public, and it must have the same name as the source file
All the top-level, non-public types will be package private —
are visible only in the package, but not outside it
Creating a Package
//in the Draggable.java file
package graphics;
public interface Draggable { . . . }
import graphics.Rectangle;
To create an instance
import java.awt.*;
import java.awt.color.*;
The Static Import Statement
Gives a way to import the constants and static methods
java.lang.Math
public static final double PI 3.141592653589793
public static double cos(double a)
...../graphics/Rectangle.java
References