Pages

Sunday, June 10, 2012

Abstract classes


An abstract class can be defined as the beginnig of a class. It implements abstract methods that can be used and modified in subclasses which extends the abstract one. The abstract methods do not have a body, the body must be implemented in the subclasses. An example can be the following: a first abstract class is Shape, the second one y Square which extends the first one. Then the Square class can use the methods and variables of the Shape class. Not all the abstract methods must be implemented. Here is an example:
public abstract class Shape{
public abstract void setName(String name);
public abstract void setNumberOfFaces(int faces);
}
public class Square extends Shape{
private String name;
public void setName(String name){
this.name = name;
}
}
public class Cube extends Shape{
private String name;
private int faces;
public void setName(String name){
this.name = name;
}
public void setNumberOfFaces(int faces){
this.faces = faces;
}
}

No comments:

Post a Comment