0% found this document useful (0 votes)
20 views51 pages

Programming Language 2: Course 7

Uploaded by

Nicolae Altomi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views51 pages

Programming Language 2: Course 7

Uploaded by

Nicolae Altomi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Programming

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

 A "contract" that spells out how a software interacts with the


environment
 A reference type, similar to a class
 Can contain only constants, method signatures, and nested
types
 There are no method bodies
 Cannot be instantiated — can only be:
 implemented by classes
 extended by other interfaces
Interfaces
 public interface OperateCar {
 // constant declarations, if any
 // method signatures
 int turn(Direction direction, double
radius, double startSpeed, double
endSpeed);
 int changeLanes(Direction direction,
double startSpeed, double endSpeed);
 ......
 // more method signatures
 }
Interfaces

 To use an interface, you write a class that implements the


interface
 Instantiable class —provides a method body for each of the
methods declared in the interface.

 public class OperateBMW760i implements


OperateCar {
 int changeLanes(Direction direction,
double startSpeed, double
endSpeed){…}
 … }
Interfaces as API

 Application Programming Interface (API)


 Very common in commercial software products
 A company sells a software package that contains complex
methods that another company wants to use in its own
software product
Interfaces and Multiple
Inheritance

 Are not part of the class hierarchy, although they work in


combination with classes
 The Java programming language does not permit multiple
inheritance, but interfaces provide an alternative
 A class can inherit from only one class but it can
implement more than one interface — objects can have
multiple types:
 of their own class
 of all the interfaces that they implement
Interfaces and Multiple
Inheritance
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);
}
Interfaces — example
 interface Reader{
 public void read();}

 interface Writer{
 public void write();}

 interface Professor extends Reader,


Writer{
 int max_mark=10;
 int med_mark=5;
 int min_mark=1;
 public void evaluate();}
Interfaces — example
interface Diver {
 int h=10;
 public void diving();}
class Swimmer implements Diver {
 static final int l=50;
 public void swim() {
 System.out.println("Swims " + l +
"meters ");}
 public void diving(){
System.out.println("Dives " +
h + "meters ");}
}
Interfaces — example
 class SwimProfessor extends Swimmer
implements Professor{
public void read(){
System.out.println("Reads PRO
Sport ");}
public void write(){
System.out.println("Never
writes!");}
public void evaluate(){
System.out.println("Low. Gets
" + med_ mark);}
}
Interfaces — example
 class JavaProfessor implements
Professor {
public void read() {
System.out.println("Reads
Thinking in Java ");}
public void write() {
System.out.println("Writes
Java programs");}
public void evaluate() {
System.out.println("Excellent.
Gets " + max_mark);}
}
Interfaces — example
Interfaces — example
 public class TestInterface{
 public static void main(String [] args){
SwimProfessor sp = new
SwimProfessor();
JavaProfessor jp = new
JavaProfessor();
sp.read(); sp.write();
sp.evaluate();
jp.read(); jp.write();
jp.evaluate();
sp.swim(); sp.dive(); //correct
jp.swim(); jp.dive(); //incorrect
 }
Using an Interface as a Type

 Define a new interface — a new reference data type


 If define a reference variable whose type is an interface, any object
assigned to it must be an instance of a class that implements the
interface.

 Professor sp = new SwimProfessor();


 Professor jp = new JavaProfessor();

 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

 public interface DoItPlus extends DoIt {


 boolean didItWork(int i, double x,
String s);
 }
Abstract Classes versus
Interfaces
 All of the methods in an
interface are implicitly
abstract
 Abstract classes can
contain fields that are not
static and final, and they
can contain implemented
methods
 If an abstract class
contains only abstract
method declarations, it
should be declared as an
interface
Abstract Classes versus
Interfaces
When an Abstract Class
Implements an Interface?
 If a class does not implement all of the interface methods — the
class is declared to be abstract

 abstract class X implements Y {


 // implements all but one method of Y
 }
 class XX extends X {
 // implements the remaining method in
Y
 }
Packages
 A grouping of related types providing access protection and
name space management
 Types refers to classes, interfaces, enumerations, and
annotation types
 The types part of the Java platform are members of various
packages that bundle classes by function:
 fundamental classes — in java.lang
 classes for reading and writing — in java.io.
Packages
Packages
Creating and Using
Packages
 //in the Draggable.java file
 public interface Draggable { . . . }

 //in the Graphic.java file


 public abstract class Graphic { . . . }

 //in the Rectangle.java file


 public class Rectangle extends Graphic
implements Draggable { . . . }
 . . .
Creating and Using
Packages
 Reasons to bundle the classes and the interface in a
package:
 can easily determine that these types are related
 know where to find types that can provide graphics-
related functions
 avoid name conflict because the package creates a
new namespace
Creating and Using
Packages
 You can allow types within the package to have
unrestricted access to one another yet still restrict
access for types outside the package.

 protected int p;
Creating and Using
Packages
Creating a Package

 Choose a name for the package and put a package


statement with that name at the top of every source file that
contains the types
 The package statement (for example, package
graphics;) must be the first line in the source file
 Can be only one package statement in each source file, and
it applies to all types in the file
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 { . . . }

 //in the Graphic.java file


 package graphics;
 public abstract class Graphic { . . . }

 //in the Rectangle.java file


 package graphics;
 public class Rectangle extends Graphic
implements Draggable { . . . }
 . . .
Creating a Package

 If you do not use a package statement, your type ends up


in an unnamed package
 Only for small or temporary applications or when you are
just beginning the development process
 Classes and interfaces belong in named packages
Naming a Package

 The compiler allows many classes to have the same


name if they are in different packages
 The fully qualified name of each Rectangle class
includes the package name
 graphics.Rectangle (defined by user)
 java.awt.Rectangle (predefined)
Naming Conventions
 Package names are written in all lowercase to avoid
conflict with the names of classes or interfaces.
 Name collisions that occur within a single company
need to be handled by convention within that
company.
 Packages in the Java language itself begin with
java. or javax.
Using Package Members
 The types that comprise a package — the package
members.
 To use a public package member from outside its package:
 Refer to the member by its fully qualified name
 Import the package member
 Import the member's entire package
Referring to a Package Member
by Its Qualified Name
 Can use a package member's simple name if the code
just writing is in the same package as that member or
if that member has been imported
 If trying to use a member from a different package
and that package has not been imported, must use
the member's fully qualified name:
 graphics.Rectangle
Referring to a Package Member
by Its Qualified Name

 To create an instance of graphics.Rectangle:

 graphics.Rectangle myRectangle = new


graphics.Rectangle();

 Qualified names are all right for infrequent use, but


make the code difficult to read in repeatedly used.
Importing a Package
Member
 Put an import statement at the beginning of the file
before any type definitions but after the package
statement, if there is one

 import graphics.Rectangle;

 To create an instance

 Rectangle myRectangle = new


Rectangle();
Importing an Entire Package

 To import all the types contained in a particular


package, use the import statement with the asterisk
(*) wildcard character.
 import graphics.*;
 can refer to any class or interface in the graphics
package by its simple name.
 Circle myCircle = new Circle();
 Rectangle myRectangle = new
Rectangle();
Importing Packages

 The Java compiler automatically imports three entire


packages for each source file:
 (1) the package with no name
 (2) the java.lang package
 (3) the current package (the package for the
current file)
Apparent Hierarchies of
Packages
 Packages appear to be hierarchical, but they are
not.
 Packages in Java API
 java.awt
 java.awt.color
 java.awt.font
 Prefix java.awt (the Java Abstract Window Toolkit)
— used for a number of related packages to make
the relationship evident, but not to show inclusion.
Apparent Hierarchies of
Packages
 import java.awt.*; — imports all of the types in the
java.awt package, but it does not import java.awt.xxxx packages.

 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)

 double r = Math.cos(Math.PI * theta);

 import static java.lang.Math.PI;


 or
 import static java.lang.Math.*;

 double r = cos(PI * theta);


Managing Source and Class
Files
 Put the source code for a class, interface, enumeration, in a
text file whose name is the simple name of the type and
whose extension is .java

 // in the Rectangle.java file


 package graphics;
 public class Rectangle() { . . . }

 Put the source file in a directory whose name reflects the


name of the package to which the type belongs:

 ...../graphics/Rectangle.java
References

 The Java Tutprials. Abstract methods and classes.


https://docs.oracle.com/javase/tutorial/java/IandI/abst
ract.html
 The Java Tutorials. Interfaces.
http://java.sun.com/docs/books/tutorial/java/IandI/cre
ateinterface.html
 The Java Tutorials. Packages.
http://java.sun.com/docs/books/tutorial/java/package
/index.html

You might also like