Lecture 6
Lecture Topic:
Casting, Subclassing, Abstract classing
and No No's in Java
Any object goes into an instance of a vector
Example
Shape S;
S = (Shape) DrawnShape.elementAL( i );
Extending a class
A superclass is extended by a subclass
Shape(superclass)
- Camera(subclass)
- Target(subclass)
- Laser(subclass)
- Print(subclass)
Polymorphism -> Greek " many shapes "
send the same message to any subclass
Example
- class Print{
- static.void.ln( ){
OS.Println( );
}
- static .void.ln( double d ){
- OS.Println( d );
- }
Name Collision
Variable and method names in a subclass override those
in a super class
if variable may not be equal names, then there is
a syntax error: name collision
Inheritance n/s
Nesting
a student has a grade
a student is a person
- class student extends person{
- Grade grade = new Grade( );
Abstraction virtual methods C++ make a class abstract
to force subclassing
Abstract class can not be instanced!
- abstract class Shape{
- void Print( ){
system.out.println( "class" + this.getClass( ).getName( ) );
- }
- and methods you must overwrite
- abstract void draw( Graphics g );
- you may not make an instance of an abstract
class
- you may not make an instance of a subclass before
implementing abstract methods
- class < class name >
- [extends < class_name > ]
[implement < interface_name > ]
- {
- [<variable declaration>]
[<method declaration>]
- }
- final class Camera extends Shape{ }
- class Pentax extends Camera{ }// illegal, because
class Camera is final
- It is final!
- you may not extend a final class
- you may not override a final variable of method
- you may not set the length field method of a
array
Pentium bug
find the bug( a C++ 2.0 patch from Microsoft should
fix it!)
Example
- public class Pentium{
- public static void main( string args[ ] ){
double x = 41195835.0;
double y = 3145727.0;
double z = x - (x/y) * y;
system.out.println(z);
}
- }
- Java pentium is busted : 256
- The result should be 0.000
Applets
If a java program has main in it,
it is an application.
Else,
it is an applet.
Applets are emerged in Web pages
application run stand-alone
- public class SimpleDraw extends Applet{//SimpleDraw
is a class name here
- global variable;
public static void main(string args[ ]){
SimpleDraw Sd = new SimpleDraw( );//SimpleDraw is an applet name here
Sd.init( );
}
- }
Sample Quiz
1.If a Java program has main in it, it is
an application.
True
False
2.An abstract class can not be instanced
True
False
Last Update: 10/14/96
Copyright ©1996 - Douglas Lyon
Lyon@cse.bridgeport.edu