CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Inheritance

Inheritance
Basic skills
Superclass

Access modifiers

Keyword Description
private Available within the current class.
public Available to classes in all packages.
protected Available to classes in the same package and to subclasses.
no keyword coded Available to classes in the same package.

How to use access modifiers in a superclass

  • Access modifiers specify the accessibility of the members declared by a class.
  • A subclass can access the public and protected members of its superclass, but not the private members.

Are superclass's Constructor Inherited?

  • No. They are not inherited.
  • They are invoked explicitly or implicitly.Explicitly using the super keyword.

  • A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked.

The code for the Product superclass

import java.text.NumberFormat;

public class Product
{
    private String code;
    private String description;
    private double price;
    protected static int count = 0;   // a protected static variable

    public Product()
    {
        code = "";
        description = "";
        price = 0;
    }

    // get and set accessors for the code, description, and price
    // instance variables

    public String toString()  // override the toString method
    {
        String message =
            "Code:        " + code + "\n" +
            "Description: " + description + "\n" +
            "Price:       " + this.getFormattedPrice() + "\n";
        return message;
    }

    public static int getCount()   // create public access for the
    {                              // count variable
        return count;
    }
}
Previous | Superclass | Subclass | Overriding methods in the Superclass | Polymorphism | Next