Show code without inheritance before showing code that uses inheritance so that students create a tacit understanding of the benefits inheritance provides.

  • For example, when teaching inheritance in Java using Shape classes, developed a basic framework for displaying shapes and provided this for students.
    • Two classes Rodriguez created, Square1.java and Circle1.java, must have instance variables.
  • Later we introduce a parent class, Shape.java, which allowed us to write Square.java and Circle.java, which both extended Shape.java.
  • Providing the code that didn’t use the inheritance first was important so students could see a concrete example of what the inheritance was trying to accomplish.
  • Check out all the files Rodriguez used for this assignment.
    • Circle1 (which uses instance variables) and Circle.java (which uses inheritance) are shown below:


// Circle1.java
// Written by Brandon Rodriguez
import java.awt.Color;

public class Circle1 {
private int radius;
private int x;
private int y;
private Color color;

public Circle1(int r, int x, int y) {
radius = r;
this.x = x;
this.y = y;
color = Color.RED;
}

public double getPerimeter() {
return 2 * Math.PI * radius;
}

public double getArea() {
double area = Math.PI * radius * radius;
return area;
}

public int getRadius() {
return radius;
}

public int getX() {
return x;
}

public int getY() {
return y;
}

public Color getColor() {
return color;
}
}

// Circle.java
// This file extends Shape.java
// Written by Brandon Rodriguez
import java.awt.Color;
import java.awt.Graphics;

public class Circle extends Shape {
private int radius;

public Circle(int r, int x, int y) {
radius = r;
this.x = x;
this.y = y;
color = Color.RED;
}

public void draw(Graphics g) {
g.setColor(color);
g.drawOval(x, y, 2*radius, 2*radius);
g.fillOval(x, x, 2*radius, 2*radius);
}

public double getPerimeter() {
return 2 * Math.PI * radius;
}

public double getArea() {
double area = Math.PI * radius * radius;
return area;
}
}

More about this tip

External Source

Interview with Brandon R. Rodriguez