You are on page 1of 106

Inheritance

Inheritance is the process of using features (both


attributes and methods) from an existing class. The existing class is called the superclass and the new class, which inherits the superclass features, is called the subclass. superclass: Car subclasses: Truck, Limo & Racecar

Is-A and Has-A


The creation of new classes with the help of existing classes makes an important distinction between two approaches.

An "is-a" relationship declares a new class as a special new-and-improved case of an existing class.
In Geometry, a parallelogram "is-a" quadrilateral with special properties. A has-a relationship declares a new class composed of an existing class or classes. A line has points, a square has lines, and a cube has squares. A truck "is-a" car, but it "has-an" engine. In computer science programming an "is-a" relationship is called inheritance and a "has-a" relationship is called composition.

// Java2501.java // This program demonstrates fundamental inheritance syntax with <extends>. // Note how the superclass constructor is called before the subclass constructor. public class Java2501 { public static void main(String args[]) { System.out.println("\nJava2501.java\n"); Airplane dc10 = new Airplane(); System.out.println(); } }

class Vehicle
{

public Vehicle() { System.out.println("Vehicle Constructor\n"); } } { public Airplane() { System.out.println("Airplane Constructor\n"); }

class Airplane extends Vehicle

Inheritance Note
The constructor of the superclass must be called before the constructor of a subclass. Java automatically generates a call to the superclass constructor, even though there are only program statements to instantiate subclass objects.

// Java2502.java // This program demonstrates how multiple subclasses can inherit from the same superclass. public class Java2502 { public static void main(String args[]) { System.out.println("\nJava2502.java\n"); Airplane dc10 = new Airplane(); Truck tacoma = new Truck(); Ship qe2 = new Ship(); System.out.println(); } }

class Vehicle
{ } {

public Vehicle()

{ System.out.println("Vehicle Constructor"); }

class Airplane extends Vehicle


public Airplane() } { } { public Ship() } { System.out.println("Ship Constructor\n"); } { System.out.println("Airplane Constructor\n"); }

class Truck extends Vehicle


public Truck() { System.out.println("Truck Constructor\n"); }

class Ship extends Vehicle

// Java2503.java // This program demonstrates multi-level inheritance. public class Java2503 { public static void main(String args[]) { System.out.println("\nJava2503.java\n"); SportsCar triumph = new SportsCar(); System.out.println(); } }

class Vehicle
{
public Vehicle() } { System.out.println("Vehicle Constructor\n"); }

class Automobile extends Vehicle


{

public Automobile()
}

{ System.out.println("Automobile Constructor\n"); }

class SportsCar extends Automobile


{ public SportsCar() { System.out.println("SportsCar Constructor\n"); }

Instantiation & Construction


An object is created with the new operator. The special method that is called during the instantiation of a new object is called a constructor.

Constructor Notes
A constructor is a method with the same identifier as the class. Constructors are neither void nor return methods. A constructor is called during the instantiation of an object. Constructors without parameters are default constructors.

// Java2504.java // This program demonstrates inheritance // qualities. // Objects of the Airplane class have access // to methods of the Vehicle class. public class Java2504 { public static void main(String args[]) { System.out.println("\nJava2504.java\n"); Airplane dc10 = new Airplane(); System.out.println("Range: "+ dc10.getRange()); System.out.println("Engines: " + dc10.getEngines()); System.out.println("Capacity: " +

class Vehicle { private int capacity; // # of people it can carry private int speed; // mph top speed public Vehicle() { System.out.println("Vehicle Constructor\n"); capacity = 0; speed = 0; } public int getCapacity() { return capacity; } public int getSpeed() { return speed; } }

dc10.getCapacity());
System.out.println("Speed: "+

dc10.getSpeed());
System.out.println(); }

class Airplane extends Vehicle { private int range; // flying range private int engines; // number of engines public Airplane() { System.out.println("Airplane Constructor"); range = 0; engines = 0; } public int getRange() { return range; } public int getEngines() { return engines; } }

// Java2505.java // In this program the constructors are altered // to parameter methods. // The program will not compile because // the constructor of the superclass // cannot be called properly. public class Java2505 { public static void main(String args[]) { System.out.println("\nJava2505.java\n"); Airplane dc10 = new Airplane(5000,3); System.out.println("Range: "+ dc10.getRange()); System.out.println("Engines: " + dc10.getEngines()); System.out.println("Capacity: " + dc10.getCapacity()); System.out.println("Speed: "+ dc10.getSpeed()); System.out.println(); } }

class Vehicle { private int capacity; // # of people it can carry private int speed; // mph top speed

public Vehicle(int c, int s)


{

System.out.println("Vehicle Constructor\n");

capacity = c; speed = s;
} public int getCapacity() public int getSpeed() }

{ return capacity; } { return speed; }

class Airplane extends Vehicle { private int range; // flying range private int engines; // number of engines

public Airplane(int r, int e)


{

System.out.println("Airplane Constructor");

range = r; engines = e;

} public int getRange() { return range; } public int getEngines() { return engines; }

// Java2506.java // The problem of program Java2305.java // is solved by using the <super> keyword // to pass parameters to the superclass // constructor. public class Java2504 { public static void main(String args[]) { System.out.println("\nJava2506.java\n");

class Vehicle { private int capacity; // # of people it can carry private int speed; // mph top speed

public Vehicle(int c, int s)


{

System.out.println("Vehicle Constructor\n");

capacity = c; speed = s;
} public int getCapacity() public int getSpeed()

{ return capacity; } { return speed; }

Airplane dc10 = new Airplane(5000,3,300,600); System.out.println("Range: "+


dc10.getRange()); System.out.println("Engines: " + dc10.getEngines()); System.out.println("Capacity: " + dc10.getCapacity()); System.out.println("Speed: "+ dc10.getSpeed()); System.out.println(); }

} class Airplane extends Vehicle { private int range; // flying range private int engines; // number of engines

public Airplane(int r, int e, int c, int s)


{

super(c,s); // must be 1st statement


System.out.println("Airplane Constructor");

range = r; engines = e;
} public int getRange() { return range; } public int getEngines() { return engines; }

Passing Information to Super Classes


Information passing to constructors in an inheritance hierarchy starts by passing all information for all constructors to the constructor of the lowest subclass. In the lowest subclass the first statement must be used to pass any information to higher-level superclasses with the reserved word super. Repeat this process for every level in the inheritance hierarchy.

// Java2507.java // This program demonstrates how to use <super> // to pass information in multi-level inheritance // situations. public class Java2507 { public static void main(String args[]) { System.out.println("\nJava2507.java\n"); SportsCar triumph = new SportsCar(2500,180,140); } } class Vehicle { private int weight; // weight in lbs of the vehicle

class Automobile extends Vehicle { private int hp; // horse power of the automobile

public Automobile(int w, int h)


{

super(w);
hp = h; System.out.println("Automobile Constructor"); System.out.println("Automobile has " + hp + " horse power.\n"); } } class SportsCar extends Automobile { private int speed; // top mph of the sportscar

public SportsCar(int w, int h, int s)


{

public Vehicle(int w)
{ weight = w; System.out.println("Vehicle Constructor"); System.out.println("Vehicle weighs " + weight + " pounds.\n"); }

super(w,h);
speed = s; System.out.println("SportsCar Constructor"); System.out.println("Sportscar can go " + speed + " MPH.\n"); }

// Java2508.java // This program demonstrates how the superclass <showData> method is // overridden by the subclass <showData> method. public class Java2508 { public static void main(String args[]) { System.out.println("\nJava2508.java\n"); SportsCar triumph = new SportsCar(180,140); triumph.showData(); } } class Automobile { private int hp; public Automobile(int h) { hp = h; } public int getHP() { return hp; } class SportsCar extends Automobile { private int speed; public SportsCar(int h, int s) { super(h); speed = s; } public int getSpeed() { return speed; }

public void showData()


{ System.out.println("Sportscar has " + getHP() + " HP"); System.out.println("Sportscar can go " + getSpeed() + " MPH.\n"); } }

public void showData()


{

System.out.println("Automobile has " + hp + "HP\n"); }

// Java2509.java // This program shows how identically named methods are called for their respective objects. public class Java2509 { public static void main(String args[]) { System.out.println("\nJava2509.java\n"); SportsCar triumph = new SportsCar(180,140); triumph.showData(); Automobile lincoln = new Automobile(345); lincoln.showData(); } } class Automobile { private int hp; public Automobile(int h) { hp = h; } class SportsCar extends Automobile { private int speed; public SportsCar(int h, int s) { super(h); speed = s; }

public void showData()


{ System.out.println("Sportscar can go " + speed + " MPH.\n"); } }

public void showData()


{ System.out.println("Automobile has " + hp + " HP\n"); }

// Java2510.java // This program is not a case of a sub class method overriding a superclass method. In this situation // the <setData> method is overloaded and the appropriate method is called based on its signature. public class Java2510 { public static void main(String args[]) { System.out.println("\nJava2510.java\n"); SportsCar corvette=new SportsCar(50000.0,120); corvette.showData(); class SportsCar extends Automobile { private int speed; public SportsCar(double v, int s) { super(v); speed = s; } public int getSpeed() { return speed; }

corvette.setData(60000.0); corvette.setData(150);
corvette.showData();

}
} class Automobile { private double value; public Automobile(double v) public double getValue()

public void setData(int s)


{ speed = s; } public void showData() { System.out.println("Sportscar value: " + getValue() + " dollar value."); System.out.println("Sportscar speed: " + getSpeed() + " MPH.\n"); }

{ value = v; } { return value; } public void setData(double v) { value = v; } public void showData() { System.out.println("Automobile value: " + value + " dollar value.\n"); }

// Java2511.java // In this program both the <Person> class and the <Student> class each have a method // with the same identifier. The program returns the grade information twice and // does not know that the <getData> method of the <Person> class should also be used. public class Java2511 { public static void main(String args[]) { System.out.println("\nJava2511.java\n"); Student tom = new Student(12,17); tom.showData(); System.out.println(); } } class Person { protected int age; public Person(int a) { System.out.println( "Person Parameter Constructor"); age = a; } } class Student extends Person { protected int grade; public Student(int g, int a) { super(a); grade = g; System.out.println( "Student Parameter Constructor"); }

public int getData() { return grade; }


public void showData() { System.out.println("Student's Grade is + getData()); System.out.println("Student's Age is + getData()); }

"
"

public int getData() { return age; }

// Java2512.java // This program solves the problem of Java2511.java. The Java keyword <super> is // used to indicate that the getData method of the superclass is intended. public class Java2512 { public static void main(String args[]) { System.out.println("\nJava2512.java\n"); Student tom = new Student(12,17); tom.showData(); System.out.println(); } } class Person { protected int age; public Person(int a) { System.out.println( "Person Parameter Constructor"); age = a; } class Student extends Person { protected int grade; public Student(int g, int a) { super(a); grade = g; System.out.println( "Student Parameter Constructor"); }

public int getData() { return grade; }


public void showData() {

System.out.println("Student's Grade is + getData()); System.out.println("Student's Age is + super.getData());


}

"
"

public int getData() { return age; }


}

Using super
The keyword super used as the first statement in a constructor passes information to the super class constructor, like super(a); The same keyword super used in front of a method indicates that a method of the superclass needs to be called, like super.getData();
Information can be passed up to multiple inheritance levels, but it can only be passed one level at one time.

// Java2513.java // This program shows that the subclass does not have access to the private data of the superclass. public class Java2513 { public static void main(String args[]) { System.out.println("\nJava2513.java\n"); Student tom = new Student(); tom.showData(); System.out.println(); } } class Person { class Student extends Person { private int grade; public Student() { System.out.println( "Student Constructor\n"); grade = 12; } public void showData() { System.out.println("Student's Grade is " + grade); System.out.println("Student's Age is " + age); }

private int age;


public Person() { System.out.println("Person Constructor\n"); age = 17; } } }

// Java2514.java // This program changes private member data to "protected" data. // The Student class can now access data from the Person class. // It also shows that the main method can now access data from the Person class. // This is because when data is declared protected, it can be accessed by any method of any class, // as long as they are in the same package. This isn't the same as public, which allows unlimited access. public class Java2514 { public static void main(String args[]) { System.out.println("\nJava2514.java\n"); Student tom = new Student(); Person joe = new Person(); class Student extends Person { private int grade; public Student() { System.out.println( "Student Constructor\n"); grade = 12; } public void showData() { System.out.println("Student's Grade is " + grade); System.out.println("Student's Age is " + age); }

joe.age = 20;

tom.showData(); System.out.println(); } } class Person {

protected int age;


public Person() { System.out.println("Person Constructor\n"); age = 17; } }

public, private & protected


Attributes & methods declared public can be accessed by methods of the same class or any other class. Attributes & methods declared private can only be accessed by methods of the same class. Attributes & methods declared protected can only be accessed by methods of the same class or subclass, and yes it can also be accessed from anywhere in the same package.

AP Exam Alert
private and public access is tested
on the APCS Examination.

protected access is not tested on


the APCS Examination.

Composition
Composition occurs when the data attributes of one
class are objects of another class. You do NOT say A Car is-an Engine but you DO say A Car has-an Engine class: Car

Contained Classes: Engine Tire

Can it be both?
It is possible for a program to use both inheritance and composition. You can say A TireSwing is-a Swing. You can also say, A TireSwing has-a Tire. Note: The same Tire can be used for a Car and a Swing. superclass: Swing subclass: TireSwing Contained Class: Tire

// Java2515.java // This program demonstrates "composition", which uses multiple classes in // such a way that an object of one class becomes a data member of another class.
public class Java2515 { public static void main(String args[]) { System.out.println("\nJava2515.java\n"); System.out.println(); Car toyota = new Car("Tundra",4,8,4.7,265); // Tundra w/4 doors, 8 cylinders, 4.7 l engine & 265 hp toyota.displayCar(); System.out.println(); } } class Engine { private int cylinders; // number of cylinders in the engine private double liters; // displacement of the engine in liters private int horsePower; // horsepower of the engine public Engine(int cyl, double size, int hp) { cylinders = cyl; liters = size; horsePower = hp; System.out.println("Engine Object Finished\n"); } public int getCylinders() { return cylinders; } public double getSize() { return liters; } public int getHP() { return horsePower; } } class Car { private String carMake; private int doors;

private Engine engineObj;


public Car(String cm, int doorNum, int cyl, double size, int hp) { carMake = cm; doors = doorNum; engineObj = new Engine(cyl,size,hp); System.out.println( "Car Object Finished\n"); }

public void displayCar() { System.out.println("CarMake: + carMake); System.out.println("Doors: + doors); System.out.println("Cylinders: + engineObj.getCylinders()); System.out.println("Size: + engineObj.getSize()); System.out.println("HorsePower: + engineObj.getHP()); }
}

" " " " "

// Java2516.java // This program demonstrates multi-level composition. // A school-has-labs, and the labs-have-computers.

public class Java2516 { public static void main(String args[]) { System.out.println("\nJava2516.java\n");


// object has 12 labs with // 32 computers of 256 MB RAM System.out.println(); } } class Computer { private int ram; // computer memory public Computer(int r) {

School bhs = new School(12,32,256);

class Lab { private int compCount; // # of computers private Computer compObj; public Lab(int cc, int r) { compCount = cc;

compObj = new Computer(r);


System.out.println( "Lab Object Finished\n");

} } class School { private int labCount; // # of computer labs private Lab labObj; public School(int lc, int cc, int r) { labCount = lc;

ram = r;

System.out.println( "Computer Object Finished\n"); } } } }

labObj = new Lab(cc,r);

System.out.println( "School Object Finished\n");

Composition & Inheritance Notes


Inheritance involves an is-a relationship.
For example, a cat is-a mammal.

Composition involves a has-a relationship.


For example, a car has-an engine. Inheritance results in automatic superclass constructor calls. You need to insure that the superclass constructor gets the correct information with the super keyword.

Composition does not have this automatic constructor calling business.


You need to make sure that each "nested" object is properly constructed with the proper information.

// Java2517.java // This program attempts to use multiple inheritance.

public class Java2517 { public static void main(String args[]) class Rhombus { { System.out.println("\nJava2517.java\n"); public Rhombus() Square square1 = new Square(); { System.out.println(); System.out.println("Rhumbus Constructor\n"); } } } } class Rectangle { public Rectangle() { System.out.println( "Rectangle Constructor\n"); } } class Square extends Rectangle, extends Rhombus { public Square() { System.out.println("Square Constructor\n"); } }

Multiple Inheritance
Multiple Inheritance occurs when
one subclass inherits from two or more superclasses. This feature is available in C++.
It is not available in Java.

Multi-Level Inheritance
Animal Mammal

Multiple Inheritance
Reptile Extinct

Dinosaur Dog

Terrier

Graphics Examples and the rest of Chapter 25


In your textbook, Chapter 13 -- in its entirety -has been inserted at the end of Chapter 25.
The folder Progs13 -- in its entirety -- has been inserted into the Progs25 folder. In the same way, all of the Chapter 13 Power Point Slides have been inserted at the end of this file.

AP Exam Alert
This is an optional chapter in the AP Computer Science curriculum. The graphics concepts in this chapter and future input/output chapters will not be tested on the AP Computer Science Examination.

// Java1301.java // This program draws a series of pixels with the // <drawLine> method. This is accomplished by // using the same start and end coordinates.

import java.awt.*;
public class Java1301 extends java.applet.Applet { public void paint(Graphics g) { for (int x=100, y=100; x <= 500; x+=5, y+=5)

g.drawLine(x,y,x,y);

} }

// Java1302.java // This program draws a series of pixels with the // <fillRect> method. This approach may be better // if large pixels are necessary.

import java.awt.*;
public class Java1302 extends java.applet.Applet { public void paint(Graphics g) { for (int x=100, y=100; x <= 500; x+=5, y+=5)

g.fillRect(x,y,2,2);

} }

// Java1303.java // This program introduces the <setFont(new Font(Type,Style,Size))> method. // Type is either "Courier","TimesRoman", "Arial", or any other available font. // Style is either BOLD, ITALIC or PLAIN. Size is the point value of the font. import java.awt.*; public class Java1303 extends java.applet.Applet { public void paint(Graphics g) { g.drawString("Default Appearance with drawString",20,20); g.setFont(new Font("Courier",Font.PLAIN,20)); g.drawString("Courier 20-point plain font",20,60); g.setFont(new Font("Courier",Font.BOLD,20)); g.drawString("Courier 20-point bold font",20,100); g.setFont(new Font("TimesRoman",Font.PLAIN,36)); g.drawString("Times Roman 36-point plain font",20,180); g.setFont(new Font("TimesRoman",Font.ITALIC,36)); g.drawString("Times Roman 36-point italic font",20,260); g.setFont(new Font("Arial",Font.PLAIN,48)); g.drawString("Arial 48-point plain font",20,360); g.setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 48)); g.drawString("Arial 48-point bold and italic font",20,460); g.setFont(new Font("Qwerty",Font.PLAIN,24));
g.drawString("Arial 24-point plain font substituted for non-existent Qwerty font",20,520);

The setFont Method


g.setFont(new Font("Courier",Font.BOLD,20)); alters the default font to Courier, Bold and size 20. An object of the Font class is used to change the font.

// Java1304.java // This program draws a circle using the <cos> and <sin> methods of the <Math> // class. It is simpler to use the <drawOval> method. This program helps to // explain the next program. import java.awt.*; public class Java1304 extends java.applet.Applet { public void paint(Graphics g) { int x,y; int radius = 100; int centerX = 200; int centerY = 200; g.setColor(Color.blue); for (double radian = 0; radian <= 2 * Math.PI; radian += 0.01) { x = (int) Math.round(Math.cos(radian) * radius) + centerX; y = (int) Math.round(Math.sin(radian) * radius) + centerY; g.drawLine(x,y,x,y); } } }

// Java1305.java
// This program draws a regular hexagon using the <cos> & <sin> methods of the <Math> class.

import java.awt.*; public class Java1305 extends java.applet.Applet { public void paint(Graphics g) { int radius = 100; int centerX = 200; int centerY = 200; double twoPI = 2 * Math.PI; g.setColor(Color.blue); int x1 = (int) Math.round(Math.cos(twoPI * 1/6) * radius) + centerX; int y1 = (int) Math.round(Math.sin(twoPI * 1/6) * radius) + centerY; int x2 = (int) Math.round(Math.cos(twoPI * 2/6) * radius) + centerX; int y2 = (int) Math.round(Math.sin(twoPI * 2/6) * radius) + centerY; int x3 = (int) Math.round(Math.cos(twoPI * 3/6) * radius) + centerX; int y3 = (int) Math.round(Math.sin(twoPI * 3/6) * radius) + centerY; int x4 = (int) Math.round(Math.cos(twoPI * 4/6) * radius) + centerX; int y4 = (int) Math.round(Math.sin(twoPI * 4/6) * radius) + centerY; int x5 = (int) Math.round(Math.cos(twoPI * 5/6) * radius) + centerX; int y5 = (int) Math.round(Math.sin(twoPI * 5/6) * radius) + centerY; int x6 = (int) Math.round(Math.cos(twoPI) * radius) + centerX; int y6 = (int) Math.round(Math.sin(twoPI) * radius) + centerY; Polygon hex = new Polygon(); hex.addPoint(x1,y1); hex.addPoint(x2,y2); hex.addPoint(x3,y3); hex.addPoint(x4,y4); hex.addPoint(x5,y5); hex.addPoint(x6,y6); g.fillPolygon(hex); } }

// Java1306.java // This program draws a pentagon // with the <fillPolygon> method. // This example uses arrays of x & y // coordinates with the fillPolygon // method. import java.awt.*; import java.applet.*; public class Java1306 extends Applet { public void paint(Graphics g) { g.setColor(Color.red); int xCoord[] = {400,550,500,300,250}; int yCoord[] = {70,200,350,350,200}; g.fillPolygon(xCoord,yCoord,5); } }

// Java1307.java // This program draws a sequence // of connected lines with the // <drawPolyline> method. import java.awt.*; import java.applet.*; public class Java1307 extends Applet { public void paint(Graphics g) { g.setColor(Color.blue); int xCoord[] = {400,550,500,300,250}; int yCoord[] = {70,200,350,350,200}; g.drawPolyline(xCoord,yCoord,5); } }

// Java1308.java // This program demonstrates how to draw a regular hexagon efficiently by using // coordinates arrays inside a loop control structure. import java.awt.*; import java.applet.*; public class Java1308 extends Applet { public void paint(Graphics g) { int centerX = 400; int centerY = 300; int radius = 200; double twoPI = 2 * Math.PI; int xCoord[] = new int[6]; int yCoord[] = new int[6]; g.setColor(Color.blue); for (int k = 0; k < 6; k++) { xCoord[k] = (int) Math.round(Math.cos(twoPI * k/6) * radius) + centerX; yCoord[k] = (int) Math.round(Math.sin(twoPI * k/6) * radius) + centerY; } g.fillPolygon(xCoord,yCoord,6); } }

// Java1309.java // This program uses the regular hexagon code and creates a general regular Polygon method. import java.awt.*; import java.applet.*; public class Java1309 extends Applet { public void paint(Graphics g) { int sides = 5; for (int y = 100; y <= 500; y+=120) { for (int x = 100; x <= 800; x+=120) regPolygon(g,50,x,y,sides); sides++; } } public void regPolygon(Graphics g, int radius, int centerX, int centerY,int sides) { double twoPI = 2 * Math.PI; int xCoord[] = new int[sides]; int yCoord[] = new int[sides]; g.setColor(Color.blue); for (int k = 0; k < sides; k++) { xCoord[k] = (int) Math.round(Math.cos(twoPI * k/sides) * radius) + centerX; yCoord[k] = (int) Math.round(Math.sin(twoPI * k/sides) * radius) + centerY; } g.fillPolygon(xCoord,yCoord,sides); } }

Steps to Turn Off Warning Messages in JCreator


1. 2.
3.

Click Configure Click Options


Click JDK Tools

4.
5. 6. 7. 8.

Select Compiler in the tool type window


Click Edit Click Parameters tab Remove check from Warnings check box Click OK twice

// Java1310.java // This program counts the number of times a mouse is clicked. // Both left-clicks and right-clicks are counted using the <mouseDown> event. // Ignore the "deprecated API" warning. import java.applet.Applet; import java.awt.*;

public class Java1310 extends Applet { int numClicks;

public void init() { numClicks = 0; }


public void paint(Graphics g) { g.drawString("Mouse is clicked " + numClicks + " times.",20,20); }

public boolean mouseDown(Event e, int x, int y) { numClicks++; repaint(); return true; }


}

// Java1311.java // This program displays the position of the mouse every time it is clicked // using the <mouseDown> method. import java.applet.Applet; import java.awt.*;

public class Java1311 extends Applet { int xCoord, yCoord;


public void paint(Graphics g) { g.drawString("Mouse clicked at (" + xCoord + "," + yCoord + ")",20,20); } public boolean mouseDown(Event e, int x, int y) { xCoord = x; yCoord = y; repaint(); return true; }

// Java1312.java // This program demonstrates how to determine if the mouse is inside or // outside the Applet window using the <mouseEnter> and <mouseExit> methods. import java.applet.Applet; import java.awt.*; public class Java1312 extends Applet { boolean insideApplet; public void paint(Graphics g) { if (insideApplet) g.drawString("Mouse is inside applet",20,20); else g.drawString("Mouse is outside applet",20,20); } public boolean mouseEnter(Event e, int x, int y) { insideApplet = true; repaint(); return true; } public boolean mouseExit(Event e, int x, int y) { insideApplet = false; repaint(); return true; } }

// Java1313.java // This program determines if a mouse is clicked once or twice using the // <clickCount> method. This method works for the left or right button. import java.applet.Applet; import java.awt.*; public class Java1313 extends Applet { boolean singleClick,doubleClick;

public void paint(Graphics g) { if (singleClick) g.drawString("Mouse was clicked once",20,20); if (doubleClick) g.drawString("Mouse was clicked twice",20,20); }
public boolean mouseDown(Event e, int x, int y) { switch (e.clickCount) { case 1: singleClick = true; doubleClick = false; break; case 2: doubleClick = true; singleClick = false; } repaint(); return true; }

// Java1314.java // This program displays the position of the mouse every time it moves // using the <mouseMove> method. import java.applet.Applet; import java.awt.*;

public class Java1314 extends Applet { int xCoord, yCoord;


public void paint(Graphics g) { g.drawString("Mouse is located at (" + xCoord + "," + yCoord + ")",20,20); } public boolean mouseMove(Event e, int x, int y) { xCoord = x; yCoord = y; repaint(); return true; }

// Java1315.java // This program draws a small square at every mouse click position.

import java.applet.Applet; import java.awt.*;


public class Java1315 extends Applet { int xCoord; int yCoord; boolean firstPaint; public void init() { firstPaint = true; } public void paint(Graphics g) { if (firstPaint) firstPaint = false; else { g.setColor(Color.red); g.fillRect(xCoord,yCoord,15,15); } }

public boolean mouseDown(Event e, int x, int y) { xCoord = x; yCoord = y; repaint(); return true; } }

// Java1316.java // This program draws small squares // at every mouse click position. // The program will crash if you try // to draw more than 100 squares. import java.applet.Applet; import java.awt.*; public class Java1316 extends Applet { int xCoord[]; int yCoord[]; int numSquare; boolean firstPaint; public void init() { xCoord = new int[100]; yCoord = new int[100]; numSquare = 0; firstPaint = true; }

public void paint(Graphics g) { g.setColor(Color.red); for (int k = 0; k < numSquare; k++) g.fillRect(xCoord[k],yCoord[k],15,15); }
public boolean mouseDown(Event e, int x, int y) { xCoord[numSquare] = x; yCoord[numSquare] = y; numSquare++; repaint(); return true; }

// Java1317.java // This uses the <Rectangle> class with the // <inside> method to determine if a certain // square has been clicked. import java.applet.Applet; import java.awt.*; public class Java1317 extends Applet { Rectangle red, green, blue; int numColor; public void init() { red = new Rectangle(50,50,100,100); green = new Rectangle(50,200,100,100); blue = new Rectangle(50,350,100,100); numColor = 0; } public boolean mouseDown(Event e, int x, int y) { if(red.inside(x,y)) numColor = 1; else if(green.inside(x,y)) numColor = 2; else if(blue.inside(x,y)) numColor = 3; else numColor = 4; repaint(); return true; }

public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(50,50,100,100); g.setColor(Color.green); g.fillRect(50,200,100,100); g.setColor(Color.blue); g.fillRect(50,350,100,100); switch (numColor) { case 1: g.setColor(Color.red); g.drawString("Mouse clicked inside red", 200,75); break; case 2: g.setColor(Color.green); g.drawString("Mouse clicked inside green", 200,225); break; case 3: g.setColor(Color.blue); g.drawString("Mouse clicked inside blue", 200,375); break; case 4: g.setColor(Color.black); g.drawString( "Mouse is clicked outside the colored squares", 50,20); break; } } }

// Java1318.java // This program proves that objects of the <Rectangle> class are abstract to the viewer and // not visible. The three square are intentionally not displayed. The program still works // like the previous program, but you must guess at the location of the squares. import java.applet.Applet; import java.awt.*; public class Java1318 extends Applet { Rectangle red, green, blue; int numColor; public void init() { red = new Rectangle(50,50,100,100); green = new Rectangle(50,200,100,100); blue = new Rectangle(50,350,100,100); numColor = 0; } public boolean mouseDown(Event e, int x, int y) { if(red.inside(x,y)) numColor = 1; else if(green.inside(x,y)) numColor = 2; else if(blue.inside(x,y)) numColor = 3; else numColor = 4; repaint(); return true; } public void paint(Graphics g) { switch (numColor) { case 1: g.setColor(Color.red); g.drawString("Mouse clicked inside red", 200,75); break; case 2: g.setColor(Color.green); g.drawString("Mouse clicked inside green", 200,225); break; case 3: g.setColor(Color.blue); g.drawString("Mouse clicked inside blue", 200,375); break; case 4: g.setColor(Color.black); g.drawString( "Mouse is clicked outside the colored squares", 50,20); break; } } }

// Java1319.java // This program draws a straight line from the point where the mouse is clicked // to the point where the mouse is released. import java.applet.Applet; import java.awt.*; public class Java1319 extends Applet { int startX,startY,endX,endY;

public void paint(Graphics g) { g.drawLine(startX,startY,endX,endY); }


public boolean mouseDown(Event e, int x, int y) { startX = x; startY = y; return true; } public boolean mouseUp(Event e, int x, int y) { endX = x; endY = y; repaint(); return true; } }

// Java1320.java // This program draws a straight line from the point where the mouse is clicked // to the point where the mouse is released. In this example the line is constantly visible. import java.applet.Applet; import java.awt.*; public class Java1320 extends Applet { int startX,startY,endX,endY;

public void paint(Graphics g) { g.drawLine(startX,startY,endX,endY); }


public boolean mouseDown(Event e, int x, int y) { startX = x; startY = y; return true; }

public boolean mouseDrag(Event e, int x, int y) { endX = x; endY = y; repaint(); return true; }
}

// Java1321.java // This program draws a straight line // from the point where the mouse is // clicked to the point where the // mouse is released. Additionally, // the program stores the lines // coordinate information in arrays // so that all the lines are visible. import java.applet.Applet; import java.awt.*; public class Java1321 extends Applet { int[] startX,startY,endX,endY; int currentStartX,currentStartY; int currentEndX,currentEndY; boolean currentLineDone; int lineCount; public void init() { startX = new int[100]; startY = new int[100]; endX = new int[100]; endY = new int[100]; lineCount = 0; currentLineDone = false; }

public void paint(Graphics g) {

for (int k = 0; k < lineCount; k++) g.drawLine(startX[k],startY[k],endX[k],endY[k]);


if (!currentLineDone) g.drawLine(currentStartX,currentStartY,currentEndX,currentEndY); currentLineDone = false;

} public boolean mouseDown(Event e, int x, int y) { currentStartX = x; currentStartY = y; return true; } public boolean mouseDrag(Event e, int x, int y) { currentEndX = x; currentEndY = y; repaint(); return true; } public boolean mouseUp(Event e, int x, int y) { addLine(x,y); currentLineDone = true; return true; }

public void addLine(int x, int y) { startX[lineCount] = currentStartX; startY[lineCount] = currentStartY; endX[lineCount] = x; endY[lineCount] = y; lineCount++; repaint(); }}

// Java1322.java // This program demonstrates a simple // mouse draw approach. import java.applet.Applet; import java.awt.*; public class Java1322 extends Applet {

int[] xCoord,yCoord; int pointCount;


public void init() { xCoord = new int[10000]; yCoord = new int[10000]; pointCount = 0; }

public boolean mouseDrag(Event e, int x, int y) { xCoord[pointCount] = x; yCoord[pointCount] = y; pointCount++; repaint(); return true; } }

public void paint(Graphics g) { g.setColor(Color.red); for (int k = 0; k < pointCount; k++) g.fillRect(xCoord[k],yCoord[k],2,2); }

Understanding Graphics Displays


Imagine that the video card has a bunch of color code boxes. Box code number 4 contains the RGB value of (255,0,0) which is bright red. This gives us the following sequence of operations: Some method call places the color code 4 in the video memory. The video card identifies that code 4 is bright red. A bright-red pixel is now displayed on the monitor at coordinate (0,0).

Virtual Memory & Video Buffering

// Java1323.java // This program creates an applet window with a black background. import java.awt.*; import java.applet.Applet; public class Java1323 extends Applet { int appletWidth; // width of the Applet window int appletHeight; // height of the Applet window public void init() { appletWidth = getWidth(); appletHeight = getHeight(); }

public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0,0,appletWidth,appletHeight); } }

// Java1324.java This program introduces the <drawSnowman> method. import java.awt.*; import java.applet.*; public class Java1324 extends Applet { int appletWidth; // width of the Applet window int appletHeight; // height of the Applet window public void init() { appletWidth = getWidth(); appletHeight = getHeight(); } public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0,0,appletWidth,appletHeight); drawSnowman(g,20,200); } public void drawSnowman(Graphics g, int x, int y) { g.setColor(Color.WHITE); g.fillOval(x+20,y,40,40); g.fillOval(x+10,y+35,60,60); g.fillOval(x,y+90,80,80); } }

// Java1325.java // This program adds the <eraseSnowman> method to the <drawSnowman> method. // The snowman is not visible because it is erased as quickly as it is drawn. import java.awt.*; import java.applet.*; public class Java1325 extends Applet { int appletWidth; // width of the Applet window int appletHeight; // height of the Applet window public void init() { appletWidth = getWidth(); appletHeight = getHeight(); } public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0,0,appletWidth,appletHeight); for (int x = 20; x < 700; x += 100) { drawSnowman(g,x,200); eraseSnowman(g,x,200); } } public void drawSnowman(Graphics g, int x, int y) { g.setColor(Color.WHITE); g.fillOval(x+20,y,40,40); g.fillOval(x+10,y+35,60,60); g.fillOval(x,y+90,80,80); } public void eraseSnowman(Graphics g, int x, int y) { g.setColor(Color.BLACK); g.fillRect(x,y,80,170); }

Important Note
The next few programming examples demonstrate computer animation. While an attempt will be made to duplicate the animation affects with PowerPoint, you need to compile and execute the programs for yourself to truly see the program output.

// Java1326.java // This program adds a <delay> method, which makes it possible to see the snowman movement.

import java.awt.*; import java.applet.*;


public class Java1326 extends Applet { int appletWidth; // width of Applet window int appletHeight;// height of Applet window public void init() { appletWidth = getWidth(); appletHeight = getHeight(); } public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0,0,appletWidth,appletHeight); for (int x = 20; x < 700; x += 10) { drawSnowman(g,x,200); delay(50); eraseSnowman(g,x,200); } }

public void drawSnowman(Graphics g, int x, int y) { g.setColor(Color.WHITE); g.fillOval(x+20,y,40,40); g.fillOval(x+10,y+35,60,60); g.fillOval(x,y+90,80,80); } public void eraseSnowman(Graphics g, int x, int y) { g.setColor(Color.BLACK); g.fillRect(x,y,80,170); } public void delay(int n) { long startDelay = System.currentTimeMillis(); long endDelay = 0; while (endDelay - startDelay < n) endDelay = System.currentTimeMillis(); } }

// Java1327.java // This program demonstrates that the "draw and erase" animation approach // does not work on a multi-colored background.
import java.awt.*; import java.applet.*; import java.util.*; public class Java1327 extends Applet { int appletWidth; // width of Applet window int appletHeight; // height of Applet window public void init() { appletWidth = getWidth(); appletHeight = getHeight(); } public void paint(Graphics g) { g.setColor(Color.BLACK); createBackGround(g); for (int x = 20; x < 700; x += 10) { drawSnowman(g,x,200); delay(50); eraseSnowman(g,x,200); } } public void createBackGround(Graphics g) { Random rnd = new Random(12345); for (int k = 1; k <= 1000; k++) { int rndX = rnd.nextInt(750); int rndY = rnd.nextInt(550); g.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256),rnd.nextInt(256))); g.fillRect(rndX,rndY,50,50); } } // These 3 methods are the same as before public void drawSnowman(Graphics g, int x, int y) public void eraseSnowman(Graphics g, int x, int y) public void delay(int n) }

// Java1328.java // This program cures the animation problem with virtual memory, buffer methods.
import java.awt.*; import java.applet.*; import java.util.*; public class Java1328 extends Applet { int appletWidth; // width of Applet window int appletHeight; // height of Applet window Image virtualMem; Graphics gBuffer; public void init() { appletWidth = getWidth(); appletHeight = getHeight(); virtualMem = createImage(appletWidth, appletHeight); gBuffer = virtualMem.getGraphics(); } public void drawSnowman(Graphics g, int x, int y) { createBackGround(); gBuffer.setColor(Color.WHITE); gBuffer.fillOval(x+20,y,40,40); gBuffer.fillOval(x+10,y+35,60,60); gBuffer.fillOval(x,y+90,80,80); g.drawImage (virtualMem,0,0, this); } public void createBackGround() { Random rnd = new Random(12345); for (int k = 1; k <= 1000; k++) { int rndX = rnd.nextInt(750); int rndY = rnd.nextInt(550); gBuffer.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256),rnd.nextInt(256))); gBuffer.fillRect(rndX,rndY,50,50); } } public void delay(int n) // same as before

public void paint(Graphics g) { for (int x = 20; x < 700; x += 5) { drawSnowman(g,x,200); delay(10); } }

// Java1329.java // This program uses virtual memory for a simple draw program. // The program will flicker while drawing. import java.applet.Applet; import java.awt.*; public class Java1329 extends Applet { Image virtualMem; Graphics gBuffer; int oldX, oldY, newX, newY; int appletWidth, appletHeight; public void init() { appletWidth = getWidth(); appletHeight = getHeight(); virtualMem = createImage(appletWidth,appletHeight); gBuffer = virtualMem.getGraphics(); gBuffer.setColor(Color.white); gBuffer.fillRect(0,0,appletWidth,appletHeight); } public void paint(Graphics g) { gBuffer.setColor(Color.black); gBuffer.drawString("Move inside the applet to draw", 20,20); gBuffer.setColor(Color.blue); gBuffer.fillRect(oldX,oldY,2,2); g.drawImage(virtualMem,0,0,this); } public boolean mouseDown( Event e, int x, int y) { newX = x; newY = y; oldX = newX; oldY = newY; repaint(); return true; } public boolean mouseDrag( Event e, int x, int y) { newX = x; newY = y; oldX = newX; oldY = newY; repaint(); return true; }

// Java1330.java // This program adds the <update> methods which stabilizes the flicker of the // Java1322.java and Java1329.java programs. import java.applet.Applet; import java.awt.*; public class Java1330 extends Applet { Image virtualMem; Graphics gBuffer; int oldX, oldY, newX, newY; int appletWidth, appletHeight; public void init() { appletWidth = getWidth(); appletHeight = getHeight(); virtualMem = createImage(appletWidth,appletHeight); gBuffer = virtualMem.getGraphics(); gBuffer.setColor(Color.white); gBuffer.fillRect(0,0,appletWidth,appletHeight); } public void paint(Graphics g) { gBuffer.setColor(Color.black); gBuffer.drawString("Move inside the applet to draw", 20,20); gBuffer.setColor(Color.blue); gBuffer.fillRect(oldX,oldY,2,2); g.drawImage(virtualMem,0,0,this); } // These 2 methods // are the same as before public boolean mouseDown( Event e, int x, int y) public boolean mouseDrag( Event e, int x, int y)

public void update( Graphics g) { paint(g); }

// Java1331.java // This program draws small squares using the <update> method rather than // using arrays to store coordinate values. import java.applet.Applet; import java.awt.*; public class Java1331 extends Applet { int xCoord; int yCoord; boolean firstPaint; public void init() { firstPaint = true; } public void paint(Graphics g) { if (firstPaint) firstPaint = false; else { g.setColor(Color.red); g.fillRect(xCoord,yCoord,15,15); } } } public boolean mouseDown(Event e, int x, int y) { xCoord = x; yCoord = y; repaint(); return true; } public void update(Graphics g) { paint(g); }

// Java1332.java // This program revisits the earlier Java1320.java program using the <update> method. // It shows that <update> can cause an unwanted side effect. import java.applet.Applet; import java.awt.*; public class Java1332 extends Applet { int startX,startY,endX,endY; public void paint(Graphics g) { g.drawLine(startX,startY,endX,endY); } public void update(Graphics g) { paint(g); } public boolean mouseDown(Event e, int x, int y) { startX = x; startY = y; return true; } public boolean mouseDrag(Event e, int x, int y) { endX = x; endY = y; repaint(); return true; } }

// Java1333.java // This program demonstrates how to display a graphics image from a gif file // at any x,y location on the screen. import java.awt.*; public class Java1333 extends java.applet.Applet { Image picture; public void init() { picture = getImage(getDocumentBase(),"LSchram.gif"); } public void paint(Graphics g) { g.drawImage(picture,0,0,this); g.drawImage(picture,600,150,this); g.drawImage(picture,300,400,this); }

// Java1334.java // This program demonstrates displaying different images of different types. // It also shows that only gif and jpg files can be displayed. // The bmp file will not display. import java.awt.*; public class Java1334 extends java.applet.Applet { Image picture1, picture2, picture3; public void init() { picture1 = getImage(getDocumentBase(),"LSchram.gif"); picture2 = getImage(getDocumentBase(),"JSchram.jpg"); picture3 = getImage(getDocumentBase(),"ShortCircuit.bmp"); } public void paint(Graphics g) { g.drawImage(picture1,0,0,this); g.drawImage(picture2,300,0,this); g.drawImage(picture3,100,400,this); }

// Java1335.java // This program adds 2 ANIMATED gifs to the display. // While this does work, it causes an annoying screen flicker. import java.awt.*; public class Java1335 extends java.applet.Applet { Image picture1, picture2, picture3, picture4, picture5; public void init() { picture1 = getImage(getDocumentBase(),"LSchram.gif"); picture2 = getImage(getDocumentBase(),"JSchram.jpg"); picture3 = getImage(getDocumentBase(),"ShortCircuit.bmp"); picture4 = getImage(getDocumentBase(),"Connect.gif"); picture5 = getImage(getDocumentBase(),"Error.gif"); } public void paint(Graphics g) { g.drawImage(picture1,0,0,this); g.drawImage(picture2,300,0,this); g.drawImage(picture3,100,400,this); g.drawImage(picture4,300,400,this); g.drawImage(picture5,500,400,this); } }

// Java1336.java // This program cures the flickering caused by the ANIMATED gifs by using the update method // NOTE: Do not expect to get any "animation bonus points" for using ANIMATED gifs // in any graphics project. You will lose points instead! import java.awt.*; public class Java1336 extends java.applet.Applet { Image picture1, picture2, picture3, picture4, picture5; public void init() { picture1 = getImage(getDocumentBase(),"LSchram.gif"); picture2 = getImage(getDocumentBase(),"JSchram.jpg"); picture3 = getImage(getDocumentBase(),"ShortCircuit.bmp"); picture4 = getImage(getDocumentBase(),"Connect.gif"); picture5 = getImage(getDocumentBase(),"Error.gif"); } public void paint(Graphics g) { g.drawImage(picture1,0,0,this); g.drawImage(picture2,300,0,this); g.drawImage(picture3,100,400,this); g.drawImage(picture4,300,400,this); g.drawImage(picture5,500,400,this); } public void update(Graphics g) { paint(g); } }

// Java1337.java // This program attempts to display multiple pages of graphics output. // The program does not compile because there is no access to the graphics object g. import java.awt.*; public class Java1337 extends java.applet.Applet { int numClicks;

public void init() { numClicks = 0; }


public void paint(Graphics g) { }

public boolean mouseDown(Event e, int x, int y) { numClicks++; switch (numClicks) { case 0: g.drawString("TITLE PAGE",200,100); break; case 1: g.drawString("PAGE 2",200,300); break; case 2: g.drawString("PAGE 3",200,500); break; } repaint(); return true; } }

// Java1338.java // This program attempts to display multiple pages of graphics output. // While adding the "Graphics g" in the mouseDown parameter list allows // the program to compile, it also makes it no longer the mouseDown EVENT. // Now you have a mouseDown METHOD that has no way of being called. import java.awt.*; public class Java1338 extends java.applet.Applet { int numClicks; public void init() { numClicks = 0; } public void paint(Graphics g) { }

public boolean mouseDown(Event e, int x, int y, Graphics g) { numClicks++; switch (numClicks) { case 0: g.drawString("TITLE PAGE",200,100); break; case 1: g.drawString("PAGE 2",200,300); break; case 2: g.drawString("PAGE 3",200,500); break; } repaint(); return true; } }

// Java1339.java // This program shows the correct way to display multiple pages of graphics output. // Remember... graphics commands CANNOT be executed by EVENTS. // They can only be executed by the paint method, or by methods called from the paint method. // Events are used to manipulate the values of variables used by the paint method. import java.awt.*; public class Java1339 extends java.applet.Applet { int numClicks; public void init() { numClicks = 0; } public void paint(Graphics g) { switch (numClicks) { case 0: page1(g); break; case 1: page2(g); break; case 2: page3(g); break; } } public boolean mouseDown(Event e, int x, int y) { numClicks++; repaint(); return true; }

public void page1(Graphics g) { g.setFont(new Font("Arial",Font.BOLD,100)); g.drawString("TITLE PAGE",200,100); g.setColor(Color.red); g.fillRect(300,300,200,200); g.setFont(new Font("Times Roman",Font.PLAIN,20)); g.drawString("Click once to continue",100,500); } public void page2(Graphics g) { g.setFont(new Font("Arial",Font.BOLD,100)); g.drawString("PAGE 2",200,300); g.setColor(Color.blue); g.fillRect(0,0,100,100); g.setFont(new Font("Times Roman",Font.PLAIN,20)); g.drawString("Click once to continue",100,500); } public void page3(Graphics g) { g.setColor(Color.green); g.fillRect(100,100,300,300); g.setFont(new Font("Arial",Font.BOLD,100)); g.drawString("PAGE 3",200,500); g.setFont(new Font("Times Roman",Font.PLAIN,20)); g.drawString("Click to exit",400,600); } }

You might also like