Escolar Documentos
Profissional Documentos
Cultura Documentos
Overriding
❂ Don't confuse the concepts of overloading and
overriding
StaffMember
Volunteer Employee
Executive Hourly
2
Indirect Access I
3
Indirect Access II
class FoodItem
{
final private int CALORIES_PER_GRAM = 9;
private int fatGrams;
protected int servings;
5
Inheritance Example
class Point {
public Point( int x, int y) {
setPoint(x, y);
}
public Point() {
this(0, 0);
}
public void setPoint( int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return “(“ + x + “,” + y + “)”;
}
public int getX() {return x; } // get x coordinate
public int getY() { return y; } // get y coordinate
protected int x,y; // accessible by derived classes 6
}
Example (cntnd.)
class Circle extends Point {
private double radius;
public Circle(int x, int y, double r) {
super(x, y);
setRadius( r );
}
public Circle() { // done automatically anyway
this(0, 0, 0);
}
public void setRadius( double r ) {
radius = ( r >= 0 ? r : 0 );
}
public double getRadius() { return radius; }
public double getArea() {
return Math.PI* radius * radius;
}
public String toString() {
return “(“ + super.toString() + “,” + radius + “)”;
}
} 7
Example (cntnd.)
class Cylinder extends Circle {
private double height;
public Cylinder(double h, double r, int x, int y ) {
super( r, x, y ) // call base-class constructor
setHeight( h );
}
public void setHeight( double h ) {
height = h > 0 ? h : 0;
}
public double getHeight() { return height; }
public double getArea() {
return 2 * super.area() +
2 * Math.PI * getRadius() * height;
}
public double getVolume() {
return super.area() * height;
}
public String toString() {
return “(“ + super.toString() + “,” + height + “)”;
} 8
}
The class hierarchy:
Point
Pixel Circle
Cylinder
Final classes and final methods
10
Constructor Invocation
11
Inheritance hierarchy
public class NoInheritence {
public NoInheritence() {
System.out.println("No Inheritance.");
}
}