Home

Polymorphism and Abstraction

 

Abstract Classes

 

Introduction

In a program, you can create a class whose role is only meant to provide fundamental characteristics for other classes. This type of class cannot be used to declare a variable. Such a class is referred to as abstract. Therefore, an abstract class can be created only to serve as a parent class for other classes.

 

Practical LearningPractical Learning: Introducing Abstraction

  1. Start NetBeans and create a Java Application named ElectronicStore3
  2. To create a new class, in the Projects window, under the ElectronicStore3 folder, right-click the ElectronicStore3 sub-folder -> New -> Java Class...
  3. Set the Name to DigitalCamera and click Finish

Creating an Abstract Class

To create an abstract class, type the abstract keyword to the left of its name. Here is an example:

abstract class DigitalCamera {

}

Practical LearningPractical Learning: Creating an Abstract Class

  1. Change the file as follows:
     
    /*
     * This class is used to define an abstract digital camera.
     * The word "abstract" means that other classes will define its behavior.
     */
    package electronicstore3;
    
    public abstract class DigitalCamera {
    
    }
  2. Save the file

The Fields of an Abstract Class

Because an abstract class is primarily a class, you can add fields to it. Here is an example:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double size;
}

After creating an abstract class, you cannot (yet) declare a variable from it. You must first derive a class from it. If the abstract contains only fields like our DigitalCamera class, you do not have to do anything in the derived class. Here is an example:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double size;
}

class PointAndShoot extends DigitalCamera {
}
 

Practical LearningPractical Learning: Adding Fields to an Abstract Class

  1. Change the file as follows:
     
    /*
     * This class is used to define an abstract digital camera.
     * The word "abstract" means that other classes will define its behavior.
     */
    package electronicstore3;
    
    public abstract class DigitalCamera {
        String make;
        String model;
        double megapixels;
        double price;
    }
  2. To create a new class, in the Projects window, under the ElectronicStore3 folder, right-click the ElectronicStore3 sub-folder -> New -> Java Class...
  3. Set the Name to PointAndShoot and click Finish
  4. Change the file as follows:
     
    package electronicstore3;
    
    /**
     * This PointAndShoot class is derived from the abstract DigitalCamera class
     * A point and shoot camera is a regular camera that a person can hold
     * and take a picture.
     */
    public class PointAndShoot extends DigitalCamera {
    
    }
  5. Save the file

Using an Abstract Class

To use the class or its parent, you can declare a variable using it. Then use its fields as you see fit. For example, you can assign values to the fields. Here are examples:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double price;
}

class PointAndShoot extends DigitalCamera {
}

public class Exercise {
    public static void main(String[] args) {
	PointAndShoot camera = new PointAndShoot();

	camera.make = "Canon";
	camera.model = "Powershot A590 IS";
	camera.megapixels = 8.0;
	camera.price = 129.95;
    }
}

In our introduction, we mentioned that you could not declare a variable using an abstract class. In reality you can. One of the rules you must follow is that, if using the new operator, you must use the derived class to initialize the variable. Here is an example:

abstract class DigitalCamera {

}

class PointAndShoot extends DigitalCamera {

}

public class Exercise {
    public static void main(String[] args) {
	DigitalCamera camera = new PointAndShoot();
    }
}

After declaring and initializing the variable using the derived class, you can access the members of the abstract class, just as done earlier.

Practical LearningPractical Learning: Using an Abstract Class

  1. Access the Main.java file and change it as follows:
     
    package electronicstore3;
    
    public class Main {
    
        public static void main(String[] args) {
            DigitalCamera camera = new PointAndShoot();
    
    	camera.make = "Canon";
    	camera.model = "Powershot A590 IS";
    	camera.megapixels = 8.0;
    	camera.price = 129.95;
    
    	System.out.println("Digital Camera");
    	System.out.printf("Make:       %s\n", camera.make);
    	System.out.printf("Model:      %s\n", camera.model);
    	System.out.printf("Megapixels: %.2f\n", camera.megapixels);
    	System.out.printf("Price:      %.2f", camera.price);
        }
    
    }
  2. Execute the application to see the result:
     
    Digital Camera
    Make:       Canon
    Model:      Powershot A590 IS
    Megapixels: 8.00
    Price:      129.95

The Methods of an Abstract Class

Like a normal class, an abstract class can contain one or more methods. Here is an example:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double price;
   
    void describe() {
	System.out.println("Digital Camera");
	System.out.printf("Make:       %s\n", make);
	System.out.printf("Model:      %s\n", model);
	System.out.printf("Megapixels: %.2f\n", megapixels);
	System.out.printf("Price:      %.2f", price);
    }
}

After adding a method to the abstract class, you can declare a variable from it and access that method using an instance of the derived class.

Because a class derived from an abstract is primarily a normal class, you can add new members to it. Here is an example:

public class PointAndShoot extends DigitalCamera {
    void create() {
        make = "Canon";
	model = "Powershot A590 IS";
	megapixels = 8.0;
	price = 129.95;
    }
}

When you declare a variable using the abstract class, you cannot access the members of the derived class. This means that the following code will produce an error:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double price;
   
}

class PointAndShoot extends DigitalCamera {
    void describe() {
	System.out.println("Digital Camera");
	System.out.printf("Make:       %s\n", make);
	System.out.printf("Model:      %s\n", model);
	System.out.printf("Megapixels: %.2f\n", megapixels);
	System.out.printf("Price:      %.2f", price);
    }
}

public class Exercise {
    public static void main(String[] args) {
	DigitalCamera camera = new PointAndShoot();

	camera.make = "Olympus";
	camera.model = "FE-170";
	camera.megapixels = 6.0;
	camera.price = 119.95;

	camera.describe();
    }
}

Practical LearningPractical Learning: Adding Methods to an Abstract Class

  1. Access the DigitalCamera.java file
  2. To create a method in an abstract class, make the following change:
     
    /*
     * This class is used to define an abstract digital camera.
     * The word "abstract" means that other classes will define its behavior.
     */
    package electronicstore3;
    
    public abstract class DigitalCamera {
        String make;
        String model;
        double megapixels;
        double price;
        
        void describe() {
    	System.out.println("Digital Camera");
    	System.out.printf("Make:       %s\n", make);
    	System.out.printf("Model:      %s\n", model);
    	System.out.printf("Megapixels: %.2f\n", megapixels);
    	System.out.printf("Price:      %.2f", price);
        }
    }
  3. Access the PointAndShoot.java file
  4. To create a method in the derived class, make the following change:
     
    package electronicstore3;
    
    /**
     * This PointAndShoot class is derived from the abstract DigitalCamera class
     * A point and shoot camera is a regular camera that a person can hold
     * and take a picture.
     */
    public class PointAndShoot extends DigitalCamera {
        void create() {
            make = "Canon";
    	model = "Powershot A590 IS";
    	megapixels = 8.0;
    	price = 129.95;
        }
    }
  5. Access the Main.java file and change it as follows:
     
    package electronicstore3;
    
    public class Main {
    
        public static void main(String[] args) {
            PointAndShoot camera = new PointAndShoot();
    
            camera.create();
            camera.describe();
        }
    }
  6. Execute the application to see the result

Abstract and Pure Abstract Classes

 

Introduction

The most common reason for creating an abstract class is to have a class that would be used as a base class for future inheritance. In such a class, you do not implement any of its methods. The class is only used as a foundation for other classes. Such a class is referred to as pure abstract.

Creating a Pure Abstract Class

To create a pure abstract class, add the fields and methods that its derived classes would share. Do not implement any method in the class. You only declare the members.

To create a class that is used only as a base for other classes, type the abstract keyword on the left side of each member, especially each method, but do not implement any method. This means that each method is declared with either void or its return type, followed by the name of the class, its parentheses, its arguments if any, and a semi-colon. Here is an example:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double price;
   
    abstract void describe();
}

After creating the abstract class, once again, in order to use it, you must first derive a class from it. This time, you must implement each method of the abstract class. Here is an example:

abstract class DigitalCamera {
    String make;
    String model;
    double megapixels;
    double price;
   
    abstract void describe();
}

class PointAndShoot extends DigitalCamera {
    void describe() {
	System.out.println("Digital Camera");
	System.out.printf("Make:       %s\n", make);
	System.out.printf("Model:      %s\n", model);
	System.out.printf("Megapixels: %.2f\n", megapixels);
	System.out.printf("Price:      %.2f", price);
    }
}

If you forget to, or do not, implement an abstract method of the parent in the derived class, the compiler would produce an error. After deriving the class, you can use it by declaring a variable from it. You can declare the variable using either the abstract class or the derived class. Then you can access the public and protected members of the abstract class. Here is an example:

abstract class DigitalCamera {
    String make;
    public String model;
    protected double megapixels;
    double price;
   
    abstract void describe();
}

class PointAndShoot extends DigitalCamera {
    void describe() {
	System.out.println("Digital Camera");
	System.out.printf("Make:       %s\n", make);
	System.out.printf("Model:      %s\n", model);
	System.out.printf("Megapixels: %.2f\n", megapixels);
	System.out.printf("Price:      %.2f", price);
    }
}

public class Exercise {
    public static void main(String[] args) {
	DigitalCamera camera = new PointAndShoot();

	camera.make = "Olympus";
	camera.model = "FE-170";
	camera.megapixels = 6.0;
	camera.price = 119.95;

	camera.describe();
    }
}

This would produce:

Digital Camera
Make:       Olympus
Model:      FE-170
Megapixels: 6.00
Price:      119.95

Because a derived class is distinct from its parent class, you can add any new members you judge necessary in the child class even if those members are nor part of the abstract class.

 
 
 

Interfaces

 

Introduction

Imagine you start creating a class and, while implementing or testing it, you find out that this particular class can be used instead as a general base that other classes can be derived from. An interface is a special class whose purpose is to serve as a template that actual classes can be based on. An interface is primarily created like a class: it has a name, a body and can have members.

To create an interface, instead of the class keyword, you use the interface keyword. Here is an example:

interface Dimension {
}

As done when creating classes, you can specify the access level of an interface. Here is an example:

public interface Size {
}

As done for a class, the members of an interface are listed in its body. In an interface, you cannot declare fields like those we have used in other classes, except constants. This means that an interface mostly contains methods and usually only methods (you can also create constants). The most important rule of an interface is that, if you declare a method in it, you cannot define that method. In other words, you can provide the signature of a method (the void or return value, the name of the method, the parentheses, and the arguments, if any, followed by a semi-colon).

Here is an example of an interface that has two methods:

public interface DigitalCamera {
    String getMake();
    String getModel();
}

An Interface as a Base

An interface is used to lay a foundation for other interfaces or other classes. For this reason, it is the prime candidate for class derivation. To derive a class from an interface, type the name of the class, followed by the implements keyword, followed by the name of the interface, and followed by the body of the new class. Here is an example of a class named PointAndShoot that implements an interface named DigitalCamera:

public class PointAndShoot implements DigitalCamera {

}

When defining a class that implements an interface, you can add or not add one or more new methods, etc. Here is an example:

interface DigitalCamera {
    String getMake();
    void setMake(String make);
    String getModel();
    void setModel(String model);
    double getMegapixels();
    void setMegaPixels(double megapixels);
    double getPrice();
    void setPrice(double value);
}

class PointAndShoot implements Size, DigitalCamera {
    void describe() {
    }
}

The primary rule of interfaces is t that, if you derive a class from an interface, you must implement all methods that were created in the interface. Once the class is ready, you can then use it as you see fit. Here is an example:

interface DigitalCamera {
    String getMake();
    void setMake(String make);
    String getModel();
    void setModel(String model);
    double getMegapixels();
    void setMegapixels(double megapixels);
    double getPrice();
    void setPrice(double value);
}

class PointAndShoot implements DigitalCamera {
    String mk;
    String mdl;
    double mp;
    double prc;

    public PointAndShoot() {
    }

    public String getMake() {
	return mk;
    }

    public void setMake(String make) {
	mk = make;
    }

    public String getModel() {
	return mdl;
    }

    public void setModel(String model) {
	mdl = model;
    }

    public double getMegapixels() {
	return mp;
    }

    public void setMegapixels(double megapixels) {
	mp = megapixels;
    }

    public double getPrice() {
	return prc;
    }

    public void setPrice(double value) {
	prc = value;
    }

    public void describe() {
	System.out.println("Digital Camera");
	System.out.printf("Make:       %s\n", mk);
	System.out.printf("Model:      %s\n", mdl);
	System.out.printf("Megapixels: %.2f\n", mp);
	System.out.printf("Price:      %.2f", prc);
    }
}

This would produce:

Digital Camera
Make:       General Electric
Model:      A830
Megapixels: 8.00
Price:      69.95

An Abstract Class Based on an Interface

You can create an abstract that is based on an interface. To do this, precede the name of the new class with the abstract keyword. Here is an example:

interface DigitalCamera {

}

abstract class StoreItem implements DigitalCamera {

}

We saw that if you create a class that implements an interface, you must define all methods declared in the interface. There is an exception to this rule. If you create an abstract class that implements an interface, since you will not implement the methods of the interface in the abstract class, you do not have to implement any method in the derived class. Here is an example:

interface DigitalCamera {
    String getMake();
    void setMake(String make);
    String getModel();
    void setModel(String model);
    double getMegapixels();
    void setMegapixels(double megapixels);
}

abstract class StoreItem implements DigitalCamera {
    String itemNumber;
    double getPrice();
    void setPrice(double value);
}

As seen for abstract classes, if you want to use the new abstract class, you must derive a new class from it. When creating a class that is based on an abstract that itself is based on an interface, you must implement all methods of the interface and all methods of the abstract. Here is an example:

interface DigitalCamera {
    String getMake();
    void setMake(String make);
    String getModel();
    void setModel(String model);
    double getMegapixels();
    void setMegapixels(double megapixels);
}

abstract class StoreItem implements DigitalCamera {
    String itemNumber;
    abstract double getPrice();
    abstract void setPrice(double value);
}

class DSLR extends StoreItem {
    String mk;
    String mdl;
    double mp;
    double prc;

    public DSLR() {
    }

    public String getMake() {
	return mk;
    }

    public void setMake(String make) {
	mk = make;
    }

    public String getModel() {
	return mdl;
    }

    public void setModel(String model) {
	mdl = model;
    }

    public double getMegapixels() {
	return mp;
    }

    public void setMegapixels(double megapixels) {
	mp = megapixels;
    }

    public double getPrice() {
	return prc;
    }

    public void setPrice(double value) {
	prc = value;
    }
}

Of course, in the new class, you can add new fields and/or methods if you judge them necessary. After creating the class, you can instantiate it and access its public or protected members. Here is an example:

interface DigitalCamera {
    String getMake();
    void setMake(String make);
    String getModel();
    void setModel(String model);
    double getMegapixels();
    void setMegapixels(double megapixels);
}

abstract class StoreItem implements DigitalCamera {
    String itemNumber;
    abstract double getPrice();
    abstract void setPrice(double value);
}

class DSLR extends StoreItem {
    private String mk;
    private String mdl;
    private double mp;
    private double prc;

    public DSLR() {
    }

    public String getMake() {
	return mk;
    }

    public void setMake(String make) {
	mk = make;
    }

    public String getModel() {
	return mdl;
    }

    public void setModel(String model) {
	mdl = model;
    }

    public double getMegapixels() {
	return mp;
    }

    public void setMegapixels(double megapixels) {
	mp = megapixels;
    }

    public double getPrice() {
	return prc;
    }

    public void setPrice(double value) {
	prc = value;
    }

    public String maximumResolution;

    public void describe() {
	System.out.println("Digital Camera");
	System.out.printf("Item #:     %s\n", itemNumber);
	System.out.printf("Make:       %s\n", mk);
	System.out.printf("Model:      %s\n", mdl);
	System.out.printf("Megapixels: %.2f\n", mp);
	System.out.printf("Max Res.:   %s\n", maximumResolution);
	System.out.printf("Price:      %.2f", prc);
    }
}

public class Exercise {
    public static void main(String[] args) {
	DSLR camera = new DSLR();

	camera.itemNumber = "C29084-16";
	camera.setMake("Canon");
	camera.setModel("EOS 450D");
	camera.setMegapixels(12.2);
	camera.maximumResolution = "4272 x 2848";
	camera.setPrice(798.95);

	camera.describe();
    }
}

This would produce:

Digital Camera
Item #:     C29084-16
Make:       Canon
Model:      EOS 450D
Megapixels: 12.20
Max Res.:   4272 x 2848
Price:      798.95

Details on Implementing a Class From an Interface

Just as you can derive a class from an interface, you can create an interface that itself is based on another interface. To create such an interface, use the following formula:

modifier interface InterfaceName extends InterfaceName {
}

As you can see from this formula, you use the extends keyword instead of implements when creating an interface that extends an existing interface. Here is an example:

interface Size {
}

interface DigitalCamera {

}

interface Camcorder extends Size {

}

The Java language does not allow multiple inheritance, which is the ability to create a class based on more than one class (allowed in C++). Multiple inheritance is allowed only if the bases are interfaces. To create a multiple inheritance, separate the names of interfaces with a comma. Here is an example:

interface Size {
}

interface DigitalCamera {

}

class PointAndShoot implements Size, DigitalCamera {

}

In the previous lesson, we learned how to derive one class from another, using the extends keyword. Here is an example we use:

public class Sphere extends Circle {

}

In the same way, you can create a class that is based on another class and implements an interface. To create the class, start with the formula of deriving the class, then, use the formula of implementing an interface. 

 
 
 

Previous Copyright © 2008-2012, FunctionX Next