Introduction To Core Java (At A Glance)

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 72

At a glance

BT-GenIUS | Telecom1
Tata Consultancy Services

Anshu Katyal
Saikat Das

1
Java Features
 Full Object Oriented, Strictly & Strongly Typed Language

 Abstraction
 it provides a mechanism using which we can hide the details of

implementation.
 A good abstraction is the one that emphasizes details that are

significant and suppresses details that are not.


 Encapsulation
 Encapsulation is the process of compartmentalizing the

elements of an abstraction that constitute its structure;


encapsulation serves to separate the contractual interface of an
abstraction and its implementation.
 Abstraction is the manifestation of encapsulation.

 Inheritance
• Inheritance is a mechanism to reuse code
 Polymorphism
 Polymorphism means, behaving differently at different time

depending on the situation


2
2
Others Features
 Java
 no pointers
 Is Compiled as well as interpreted (C/C++ are Compiled)
 No Preprocessor
 No Macro
 Lots of Libraries
 Windows Applications
 Internet Applications
 Runs on the client side
 Portable
 Secure
 Multithreaded
 Distributed
 Dynamic
 Event Driven
 Easy to Learn

3
Hello WORLD!!!
Hello Class Program
public class Hello
{
public static void main(String argv[])
{
System.out.println(“Hello World!!!”);
System.exit(0);
}
}
 The System.exit method is used to return value back to
OS
System.out.println is a print statement.(Java.lang Package)

4
Compile/Execute
 The file name should be same as class name
 Class is same as an Object. Object is an instance of a Class.
 javac <filename> compiles the java code File name has a .java
extension eg. javac Hello.java

 It produces a class file (contains java byte code for Java Virtual
Machines JVM). Eg. Hello.class
 java <filename without ‘.class’> executes the program e.g. java Hello
<arguments if any>

5
Other Utilities
javap -package java.lang.Integer lists the methods and
variables that are available in the package
java.lang.Integer.
javap -c <classname>. Produces a byte code of your
program. Bytecode is written in Java Virtual Machine.
Javadoc <filename> produces a HTML file which is a
documentation of your program. One can see the
documentation using a browser.

6
Program Structure/Environment
Java
 Is interpreted (C/C++ are Compiled)
 No Preprocessor
 No #define, #ifdef, #include, ...
Main method (for Java applications)
 Embedded in a Class
public class Xyz
{
public static void main (String args[]) {

}
}
 Each class can define its own main method
 Program’s starting point depends on how the interpreter is invoked.
$ java Xyz

7
Names and Types
variables
Functions or Methods
Classes & Objects
Types of variables(8) - int, float, double, boolean,
long, byte, char,
Arrays (unlike C or C++, in Java arrays are treated as
an Object.)
Life time of a variable

8
Types of Methods and
Variables
Instance variable.
Static variables and Static Methods
public, private and protected variables and methods
Constructor Method
Automatic Variables

9
Import
Import Statement
 Without an import statement
java.util.Calendar c1;
 After the import statement

import java.util.Calendar;
...
Calendar c1;
 Saves typing

import java.util.*; // Imports all classes

10
Command Line Arguments
Command Line Args are passed to main method
public class Echo
{
public static void main(String argv[])
{
for (int i=0; i<argv.length; i++)
System.out.print(argv[i] + ” ”);
System.out.print("\n");
System.exit(0);
}
}
main has a return type of void (not int)
 The System.exit method is used to return value back to OS
The length property is used to return array size

11
Lexical Issues
Whitespace ( space, tab, newline)
Identifiers(AvgTemp , _count, $a4, 2count)
Literals(100 98.6 ‘X’ “This is a test”)
Comments(//, /*….*/, /** ….*/)
Separators (“[ ]”,”( )”,”{ }”,” ; ”,” . ”,” , ”)
Keywords (49)
abstract continue goto package synchronized assert default if
private this boolean do implements protected throw
break double import public throws byte else instanceof return
transient case extends int short try catch final interface static
void char finally long strictfp volatile class float native super
while const for new switch
12
Data Types
Integers
 long (64) –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
 Int( 32) –2,147,483,648 to 2,147,483,647
 short (16) –32,768 to 32,767
 byte (8) –128 to 127
Floating Point
 double (64) 4.9e–324 to 1.8e+308
 float (32) 1.4e−045 to 3.4e+038
Characters(Unicode)
 char (16) 10 to 255 ( 0 to 127 are same as ASCII)
Boolean
 true or false

13
•Scope & Lifetime of a Variable
•Type Conversion and Casting
Java’s Automatic Conversions
Casting Incompatible Types
Automatic Type Promotion in Expressions
The Type Promotion Rules

14
Arithmetic Operators Bitwise Operators
 Operator Result
 + Addition  Operator Result
 – Subtraction (also unary  ~ Bitwise unary NOT
minus)  & Bitwise AND
 * Multiplication  | Bitwise OR
 / Division  ^ Bitwise exclusive OR
 % Modulus  >> Shift right
 ++ Increment(Pre & Post)  >>> Shift right zero fill
 += Addition assignment  << Shift left
 –= Subtraction assignment  &= Bitwise AND assignment
 *= Multiplication assignment  |= Bitwise OR assignment
 /= Division assignment
 %= Modulus assignment
 –– Decrement

15
Relational Operators Boolean Logical Operators
 Operator Result
 == Equal to  Operator Result
 != Not equal to  & Logical AND
 > Greater than  | Logical OR
 < Less than  ^ Logical XOR (exclusive OR)
 >= Greater than or equal to  || Short-circuit OR
 <= Less than or equal to  && Short-circuit AND
 ! Logical unary NOT
 &= AND assignment
 |= OR assignment
 ^= XOR assignment
 == Equal to
 != Not equal to
 ?: Ternary if-then-else

16
Operator Precedence
 Highest
 () [] .
 ++ –– ~ !
 * / %
 + –
 >> >>> <<
 > >= < <=
 == !=
 &
 ^
 |
 &&
 ||
 ?:
 = op=
 Lowest
17
Expressions
Arithmetic expressions in Java are similar to C/C++
Example
int i = 5 + 12 / 5 - 10 % 3
= 5 + (12 / 5) - (10 % 3)
=5+2-1
=6
 Operators cannot be overloaded in Java
 Integer division vs. floating point division

18
Control Statements
If-else statement
Switch
break & continue
return
goto

Iteration Statements
for statement
while
Do while
19
For Statement
 for (i=0, j=0; (i<10) && (j<20); i++, j++)
{

}
 Comma separation is Allowed in initialization and test sections
 Makes Java syntactically closer to C
 Variable declaration
 variables can be declared within for statement, but can’t be
overloaded
int i;
for (int i=0; i<n; i++) { … } // Not valid in Java
 declaration is all or nothing

for (int i=0, j=0; … ) // Declares both i and j


 Conditional must evaluate to a boolean
 Also true for if, while

20
If, While, Do While, Switch
 These are (essentially) the same as C/C++

if (x != 2)
y=3; do {
System.out.println ("X=" + x);
if (x == 3) x *= 2;
y=7; } while(x<100);
else
y=8;
char c;
if (x >= 4) { ...
y=2; switch (c) {
k=3;
}
case 'Q':
return;
while (x<100) { case 'E':
System.out.println process_edit();
("X=" + x); break;
x *= 2;
} default:
System.out.println ("Error");
}

21
Classes
 A class is a template for an object.

Objects
 Instances of classes are called objects
 Object variables store the address of an object
 Different from primitive variables (which store the actual value)
 Primitive Data Type example
int i=3;
int j=i;
i=2;
 Object Example
java.awt.Button b1 = new java.awt.Button("OK");
java.awt.Button b2 = b1;
b2.setLabel("Cancel"); // Change is visible via b1 also
b1 = new java.awt.Button("Cancel")
 No explicit dereferencing (i.e., no &, * or -> operators)
 No pointers
 null = "Absence of reference" = a variable not pointing to an object 22
Name Space
No globals
 variables, functions, methods, constants
Scope
 Every variable, function, method, constant belongs to a Class
 Every class is part of a Package
Fully qualified name of variable or method
<package>.<class>.<member>
 Packages translate to directories in the “class path”
 A package name can contain multiple components
java.lang.String.substring()
COM.Ora.writers.david.widgets.Barchart.display()
- This class would be in the directory
“XXX/COM/Ora/writers/david/widgets”, where XXX is a
directory in the “class path”

23
Package; Import
 A package is a collection of related classes and interfaces that provides
access protection and namespace management.
 Packages are created using the package keyword
 Package Statement
 Specifies the name of the package to which a class belongs
package Simple_IO; // Must be the first statement
public class Reader {

}
 Optional
 Import Statement
 Without an import statement
java.util.Calendar c1;
 After the import statement
import java.util.Calendar;
...
Calendar c1;
 Saves typing
import java.util.*; // Imports all classes
24
Access Rules
Packages are accessible
 If associated files and directories exist and have read permission
Classes and interfaces of a package are accessible
 From any other class in the same package
 Public classes are visible from other packages
Members of a class (C) are accessible
 [Default] From any class in the same package
 Private members are accessible only from C
 Protected members are accessible from C and subclasses of C
 Public members are accessible from any class that can access C
Local variables declared within a method
 Are not accessible outside the local scope

25
Access Control
Private Default Protected Public
Class    
Sub class,
same package    

Other class,
same package    

Sub class, diff


   
package
Other class,
   
diff package
26
Data Types
Primitive Types
 Integral (byte, short, char , int, long)
 char is unsigned and also used for characters
 Floating Point (float, double)
 boolean
Classes
 Predefined classes
 String, BigInteger, Calendar, Date, Vector, ...
 Wrapper classes (Byte, Short, Integer, Long, Character)
 User defined classes
 "Special" classes
 Arrays

27
Objects are handled by Reference
Objects in Java are handled "by reference"
 Comparison is by reference
 Following is true if b1, b2 point to the same object
if (b1 == b2) { … }
if (b1.equals(b2)) { … } // member by member comparison
 Assignment copies the reference
b1 = b2;
b1.clone(b2); // Convention for copying an object
Parameters passing is always by value
 The value is always copied into the method
 For objects, the reference is copied (passed by value)
 The object itself is not copied
 It is possible to change the original object via the reference

28
Parameter Passing Example
class ParameterPassingExample {
static public void main (String[] args) {
int ai = 99;
StringBuffer as1 = new StringBuffer("Hello");
StringBuffer as2 = new StringBuffer("World");

System.out.println ("Before Call: " + show(ai, as1, as2)); Before Call : i= 99 s1='Hello'; s2='World'
set(ai,as1,as2); Before Change: i= 99 s1='Hello'; s2='World'
System.out.println ("After Call: " + show(ai, as1, as2)); After Change : i= 1 s1='Hello, World'; s2='Hello, Wo
After Call : i= 99 s1='Hello, World'; s2='World'
}
static void set (int fi, StringBuffer fs1, StringBuffer fs2) {
System.out.println ("Before Change: " + show(fi, fs1, fs2));
fi=1;
fs1.append(", World");
fs2 = new StringBuffer("Hello, World");
System.out.println ("After Change: " + show(fi, fs1, fs2));
}
static String show (int i, StringBuffer s1, StringBuffer s2) {
return "i=" + i + "s1='" + s1 + "'; s2='" + s2 + "'";
}
}

29
Constants
Constants
 Value of variable is not allowed to change after initialization
 Example
final double PI = 3.14159;
 Initialization can be done after declaration
final boolean debug_mode;

if (x<20) debug_mode = true; // Legal
else debug_mode = false; // Legal

debug_mode = false; // Error is caught at compile time
 Value of variable cannot change; value of object can change
final Button p = new Button("OK");
p = new Button ("OK"); // Illegal. P cannot point to
// a different object
p.setLabel ("Cancel"); // Legal.

30
Input/Output
java.io.OutputStream - A byte output stream
 System.out (C:stdout; C++:cout)
 System.err (C:stderr; C++:cerr)
 Convenience methods: print, println
 send characters to output streams

java.io.InputStream - A byte input stream


 System.in (C:stdin; C++:cin)
 InputStreamReader
 Reads bytes and converts them to Unicode characters
 BufferedReader
 Buffers input, improves efficiency
 Convenience method: readLine()

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader stdin = new BufferedReader (isr);
String s1 = stdin.readLine();

31
Echo.java
 A version of Echo that reads in data from System.in
import java.io.*;
class Echo {
public static void main (String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
String message;

System.out.println ("Enter a line of text:");


message = stdin.readLine();
System.out.println ("Entered: \"" + message + "\"");
} // method main
} // class Echo
 java.lang.Integer.parseInt converts a string to an integer
int message_as_int = Integer.parseInt(message);
 java.io.StreamTokenizer handles more advanced parsing

32
THANK YOU

QUESTION
???
33
BT-GenIUS | Telecom1
Tata Consultancy Services

Saikat Das
Anshu Katyal

34
Array Declaration
Array Declaration
Example
int[] scores = new int[10];
Variable type is "int[]"
Elements range from scores[0] … scores[9]
Automatic bounds checking
Each array has a public constant, length
scores.length
- this evaluates to 10
Alternate declarations
float[] prices;
float prices[];
35
Arrays
Initializer lists can be specified
int[] units = { 147, 323, 89 };
 No new operator used
 No size specified

Elements of an array can be object references


Strings[] words = new String[25];
 This reserves space to store 25 references to String objects
 String objects are not automatically created

Arrays can be passed to methods


 The reference is passed (true for all objects)
Size of array is not part of type
 A variable of type String[] can store ANY array of Strings, of
any size 36
Multi-Dimensional Arrays
Multi-dimensional arrays
A two dimensional array is an array of arrays
byte my_array[][] = new byte[2][5]
 Memory is NOT necessarily contiguous
0,0 0,1 0,2 0,3 0,4 1,0 1,1 1,2 1,3 1,4

[C] 79 87 94 82 67 98 87 81 74 91

[Java]

79 87 94 82 67 98 87 81 74 91
0,0 0,1 0,2 0,3 0,4 1,0 1,1 1,2 1,3 1,4 37
Multi-Dimensional Arrays
Each row (inner array) is independent of others
 Can reassign part of the array
my_array[1] = new byte[22];
 Each row can have a different size than other rows

int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28},
{42, 34, 37}, {13, 26, 57, 35} };
 Can have partial declarations

byte my_partial_array[][] = new byte[3][];


String lots_of_strings[][][][] = new String[5][3][][];
 All missing dimensions MUST be at the end

String more_strings[][][] = new String[5][][3]; // Not valid

38
Class Example
Declaration
import java.lang.Math;
public class Circle {
public int x, y, r; // (x,y) of Center; radius
public double circumference () { return 2 * Math.PI * r; }
public double area () { return Math.PI * r * r; }
}
Use
Circle c;
c = new Circle();
c.r = 2;
double a = c.area();
39
Constructors
 Constructors
 Perform initialization of objects
 Declaration
public class Circle {
private int x, y, r;
public Circle (int ar) { this.x=0; y=0; r=ar; }
… // Note the optional use of "this" above
}
 Use
Circle c = new Circle (2);
double a = c.area();
 Can have more than one constructor
public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }
 Can overload the default constructor
public Circle () { x=0; y=0; r=1; }
 What if a class does not define ANY constructors?
 What if a class defines constructors, but not one with NO arguments?
40
Constructors
One constructor can call another (unlike C++)
Uses "this"
public Circle (int ax, int ay, int ar) { x=ax; y=ay; r=ar; }
public Circle (int ar) { this(0, 0, ar); }
Call to an alternate constructor MUST appear first
Before any other statements
Before variable declarations

41
Class Variables
 Class variables
import java.lang.Math;
public class Circle {
static int numCircle = 0;
private int x=0, y=0, r=1; // Notice the initializers
public Circle() { num_circles++; }
public Circle (int ar) { this(); r=ar; }
public double circumference () { return 2 * Math.PI * r; }
public double area () { return Math.PI * r * r; }
}
 Referencing Class variables
 From within the class: this.numCircle (or just numCircle)

public Circle() { this.numCircle++; }


 From outside the class: Circle.num_circle

Circle c = new Circle();


System.out.println ("# Circles= " + c.numCircle);
System.out.println ("# Circles= " + Circle.numCircle);
42
Class Methods
 Class methods
import java.lang.Math;
public class Circle {
private int x,y,r;
int getX () { return this.x; }

static int numCircle = 0;


public static int getNumCircle() { return this.numCircle;}
}
 Calling class methods
 From within the class

this.getNumCircle();
 From outside the class

Circle c = new Circle();


int n1 = c.getNumCircle();
int n2 = Circle.getNumCircle();

43
(Lack of) Globals
 Java does not allow global variables
 Class variables can substitute for global variables
 Advantage: no possibility of a collision in variable names
 Example declaration in java.lang.Math:

public final static double PI;


 Example usage:

public double circumference () { return 2 * Math.PI * r; }


System.out.println ("Hello");
 Java does not allow global functions or methods
 Class methods can substitute for global functions
 Example declaration in java.lang.Integer:

public static int parseInt(String str);


 Example usage:

int i = Integer.parseInt ("73");


double sqrt_i = Math.sqrt(i);

44
Inheritance
 Need a class with ability to draw Circles
 Approach 1 (Not ideal)
public class GraphicCircle {
// Keep an instance var. to keep circle stuff
public Circle c;

// Delegate functionality to c
public double area() { return c.area(); }
public double circumference () {return c.circumference();}

// Add in GraphicCircle specific stuff


public Color outline, fill;
public void draw (Graphics page) { … }
}

45
Inheritance
 Approach 2: Inheritance
 A "GraphicCircle" isa (more specific version of) "Circle"
public class GraphicCircle extends Circle {
// Only need the 'additional' things
Color outline, fill;
public void draw (Graphics page) { … }
}
 Terms and Concepts
 Superclass, base class, parent class

 Subclass, derived class, child class

 isa, Class Hierarchy

 Inheritance of instance variables and methods Circle

Circle GraphicCircle
GraphicCircle
46
Inheritance
 GraphicCircle inherits all variables and methods
GraphicCircle gc = new GraphicCircle ();
gc.draw(); // Can invoke GraphicCircle methods
gc.x = 5; // Can access Circle fields
a = gc.area(); // Can invoke Circle methods
 GraphicCircle objects are also Circle objects
Circle c;
c = gc; // Assignment is legal
a = c.area(); // Code can treat c as any other Circle
c.draw(); // Illegal (draw is defined in GraphicCircle)

boolean b1, b2;


b1 = (c instanceof GraphicCircle); // True
b2 = (c instanceof Circle); // True

47
Class Hierarchy
 All classes (except one) have a single superclass
 No multiple inheritance
 Object is the default superclass

Object Circle GraphicCircle


 Classes and inheritance relationships form a Tree
 Called Inheritance Hierarchy
 Root of Tree is Object
 All Java classes are part of this hierarchy

Number Integer

Object Float
Boolean

String Byte 48
Constructor Chaining
A subclass invokes a superclass constructor
Explicitly - First line is a call to the superclass constructor
class GraphicCircle {

public GraphicCircle (int r, Color o, Color f) {
super(r); // Must be first line
this.outline = o;
this.fill = f;
}
Implicitly
 If first line of constructor is not a call to a constructor, super() is automatically
invoked
- What if supertype doesn't define a constructor with no arguments?
- What if first line is a call to another constructor of the form this(…)?
Note: Body of supertype constructor executes first (Like C++)!

49
Overriding Methods
 Subclass can redefine method of superclass
class Circle { …
public void reset () { x=0; y=0; r=1; }
}
class GraphicCircle { …
public void reset () {
x=0; y=0; r=1;
fill = Color.getColor ("black");
}
}
 Subclass method can call superclass method
class GraphicCircle { …
public void reset () {
super.reset();
fill = Color.getColor("black");
}
}
50
Polymorphism; Final Modifier
 Actual method to call is determined at runtime
 Depends on actual object’s type (not variable type)
Circle[] c[2];
c[0] = new Circle();
c[1] = new GraphicsCircle();
for (int i=0; i<2; i++)
c[i].reset();
 C++ requires virtual keyword to implement polymorphism
 C++ default (without keyword): resolution is done at compile time

 Java: methods are “virtual” by default polymorphism

 Can use final keyword modifier to enable compile time resolution

class Circle { …
public final void reset () { x=0; y=0; r=1; }
}
class GraphicCircle { …
public void reset () { } // No longer valid!
} 51
Finalize Methods
 Finalize: Similar to C++ destructor
 A place to clean up an object before memory is deallocated
Invoked before garbage collection
 Typically used for closing files, releasing resources, etc.
public class FileOutputStream extends OutputStream {
… // From java.io.FileOutputStream
protected void finalize() throws IOException {
if (fd != null) close(); // Closes file descriptor
}
}
 Not very common in Java (compared to C++)
 Most cleanup is done automatically by the garbage collector

 Not guaranteed to be called


 Program may exit without ever calling the finalizer

 Operating system must free any outstanding resources after exit


52
Finalize Methods
Java chains constructor methods (like C++
Java does NOT chain finalize methods
 If you define a finalizer, you should invoke the super’s
finalizer explicitly
class GraphicCircle extends Circle { …
protected void finalize () {
… local cleanup …
super.finalize();
… more local cleanup …
}
}

53
Visibility Modifiers
 Public, Private, Protected, Package
public class Circle { // With mixed visibility
public int x; // Public visibility
protected int y; // Protected visibility
int r; // Package visibility (default)
private int numCircle; // Private visibility
int area() { … }
}
 Package visibility is default
 classes in same package are friend-ly to each other

Accessible to Public Protected Package Private


Same Class Y Y Y Y
Class in same package Y Y Y N
Subclass in different package Y Y N N
Non-subclass, different package Y N N N

54
Visibility Modifier Guidelines
Public
 Use this for methods, constants that are part of the public API
 Most variables should not be public

Protected
 For members that might be useful to subclasses (e.g. Circle’s
x,y,r)
 But not for public use

Package
 For things that “cooperating classes” need access to
Private
 Fields and methods that should be hidden from everyone else

55
Circle Class
public class Circle {
protected int x=0, y=0, r=1;
private static int numCircle=0; // No one has access

/* Constructors */
public Circle () { numCircle++; }
public Circle (int ar) { this(); r=ar; }

// Public way to get to variables (final for optimization)


public final int getNumCircle() { return numCircle; }
public final int getX() { return x; }
public final int getY() { return y; }
public final int getR() { return r; }

// Methods to set variables


public void moveTo (int newx, newy) { x=newx; y=newy; }
public void move (int dx, int dy) { x+=dx; x+=dy; }
public void setRadius (double newr) { r = newr; }
}
56
Final Classes; Abstract Classes
 Final (no analogy in C++)
 Method
 Cannot be redefined by subclass
 Class
 Cannot be subclassed

public final class System extends Object { … }


public class MyClass extends System { … } // Not valid
 Abstract
 Method (analogous to a pure virtual function in C++)
 Must be redefined by subclass

 Class
 Cannot be instantiated

 If a class has an abstract method, it must be declared an abstract class

57
Abstract Class Example
public abstract class Shape {
public abstract double area(); // Note: no definition
public abstract double circumference();
}
public class Circle extends Shape {
protected int x, y, r;
public Circle(int ar) { r=ar; }
public double area() { return Math.PI * r * r; }
public double circumference() { return 2 * Math.PI * r; }
}
public class Rectangle extends Shape {
protected int x, y, w, h;
public Rectangle (int aw, int ah) { w=aw; h=ah; }
public double area() { return w * h; }
public double circumference() { return 2 * (w + h); }
}

58
Abstract Class Example
 Example usage
public static void main () { …
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(2);
shapes[1] = new Rectangle (3,4);
shapes[2] = new Rectangle (2,3);

double total_area = 0;
for (int i=0; i<shapes.length; i++)
total_area += shapes[i].area();
}
 Subclasses of Shape can be assigned to an array of Shape
 Area() method can be invoked on any kind of Shape
 Declared as an abstract method in Shape

 Not valid if area() method was not defined in Shape

59
Inheritance
 Example Hierarchy
Shape - abstract area(), circumference()
Circle - area(), circumference()
GraphicCircle - draw()

Rectangle - area(), circumference()


GraphicRectangle - draw()
 Want to have a Drawable class, with an abstract draw()

 In C++
 Multiple Inheritance
Shape

Drawable Circle Rectangle

GraphicCircle GraphicRectangle
60
Interface
 Java
 No multiple inheritance
 Java's solution: interface
public interface Drawable {
public void setColor (Color c);
public void setPosition (int x, int y);
public void draw (Graphics dw);
}
 Interface
 Looks like an abstract class; simulates some Multi-Inheritance
 But uses keyword interface instead of abstract and class

 All methods are abstract by default

 All instance variables must be constants (static and final)

 Other classes can implement an interface

61
Interface
public class GraphicRectangle
extends Rectangle implements Drawable
{
private Color c;
public GraphicRectangle (int w, int h) { super(w,h); }

// Implement each method in Drawable


public void setColor (Color ac) { c = ac; }
public void setPosition (int ax, int ay) { x=ax; y=ay; }
public void draw(Graphics dw) { ... }
}

62
Using Interfaces
Shape[] shapes = new Shape[3];
Drawable[] drawables = new Drawable[3];

GraphicCircle dc = new GraphicCircle(1);


GraphicRectangle dr = new GraphicRectangle (3,4);
GraphicCircle dc2 = new GraphicCircle(3);

// Add them to arrays


shapes[0] = dc; drawables[0] = dc;
shapes[1] = dr; drawables[1] = dr;
shapes[2] = dc2; drawables[2] = dc2;

double total_area = 0;
for (int i=0; i<shapes.length; i++) {
total_area += shapes[i].area();
drawables[i].setPosition(i*10, i*10);
drawables[i].draw(gc); // Assume gc is defined somewhere
} 63
Multiple Interfaces
 Each user defined class
 Extends exactly one other class
 Implements 0, 1, or more interface
public class GraphicRectangle
extends Rectangle
implements Drawable, java.lang.Cloneable,
java.lang.Serializable
{
...
}
 Interface
 Provides a way to simulate multiple inheritance
 Every class that implements an interface MUST define all methods of that
interface

64
Interface Hierarchy
Interfaces can be subtypes of other interfaces
Results in an interface hierarchy
 Directed, Acyclic Graph (not a tree, like the class hierarchy)
public interface Transformable
extends Scalable, Rotateable, Reflectable { ... }
public interface GraphicObject
extends Drawable, Transformable { ... }
public class Shape implements GraphicObject { ... }

65
Case Study on Inheritance
 Case Study
 Solution: Lewis: ../chap08/applications/Accounts2.java
 Bank_Account
 Generic account with ability to make deposits and withdrawals

 Savings_Account
 A kind of Bank_Account

 Collects interest
Bank_Account
 Bonus_Saver_Account
 A kind of Savings_Account

 Collects more interest Checking_Account Savings_Account


 Has penalties for withdrawal

 Checking_Account
 A kind of Bank_Account
Bonus_Saver_Account
 Has overdraft protection

66
Define Class Hierarchy
public class Bank_Account {
...
}
public class Savings_Account extends Bank_Account {
...
}
public class Bonus_Saver_Account extends Savings_Account {
...
}
public class Checking_Account extends Bank_Account {
...
}

public class Accounts2 {


public static void main (String[] args) {
... Create objects and test out class hierarchy ...
}
}

67
Define Methods
public class Bank_Account {
public Bank_Account(int account_num,double init_bal) {...}
public void deposit (double amount) { ... }
public void withdrawal (double amount) { ... }
}

public class Savings_Account extends Bank_Account {


public void add_interest () { ... }
}

public class Bonus_Saver_Account extends Savings_Account {


public void withdrawal (double amount) { ... penalty ... }
public void add_interest () { ... give bonus rate ... }
}

public class Checking_Account extends Bank_Account {


public void withdrawal (double amount)
{ ... check for overdraft ... }
} 68
Define Methods (Details)
public class Bank_Account {
protected int account;
protected double balance;

public Bank_Account(int account_num,double init_bal) {...}


Bank_Account aBA = new Bank_Account(4321, 100.00);

public void deposit (double amount) { ... }


aBA.deposit (50.00);

public void withdrawal (double amount) { ... }


aBA.withdraw (20.00);
}

69
Define Methods (Details, cont.)
public class Savings_Account extends Bank_Account {
protected double rate;

public Savings_Account (int account_num,


double initial_balance,
double interest_rate) { ... }
Savings_Account aSA = new Savings_Account (1234, 100.00, 0.05);
public void add_interest () { ... }
aSA.add_interest();
}

public class Bonus_Saver_Account extends Savings_Account {


public Bonus_Saver_Account (int account_num,
double initial_balance,
double interest_rate) { ... }
Bonus_Saver_Account aBSA = new Bonus_Saver_Account (1234, 100.00, 0.05);
public void withdrawal (double amount) { ... penalty ... }
aBSA.withdraw ( 20.00 );
public void add_interest () { ... give bonus rate ... }
aBSA.add_interest ();
}

70
Define Methods (Details, cont.)
public class Checking_Account extends Bank_Account {
private Savings_Account overdraft;

public Checking_Account (int account_number,


double initial_balance,
Savings_Account protection) {...}
Checking_Account aCA = new Checking_Account (87323, 75.00, aBSA);

public void withdrawal (double amount) {


if (checking account has enough funds)
take funds out of checking account
else if overdraft account has enough funds
take funds out of overdraft account
else
print error "Insufficient funds"
}
aCA.withdraw (20.00);
}

71
THANK YOU

QUESTION
???
72

You might also like