Instantiable classes are class (types) that are defined by a programmer to allow that or other programmers the ability to create instances (objects) of that data type. Such types are sometimes referred to as composite data types. Instantiable classes create a new type that stores multiple values as one entity. If a programmer has defined a Book class, and a Student class, they may then create instances of those data types (classes) like this:
Book b = new Book("Java for Everyone","Cay Horstmann",589) ;
Student b = new Student("Suzy Q","900111222") ;
A class is considered instantiable, if it contains instance fields and instance methods. See static vs instance (non-static) for more information about the static
modifier. A class with only static
fields and methods would not generally be considered to be an instantiable class.
Fields represent the values that are needed to represent the new data type.
// declare fields inside the class and outside methods
// class (static) fields must be assigned initial values when declared
public static final String WIDGET_CORP = "ACME Widgets";
private static int numberOfWidgets = 0;
private final int WIDGET_ID;
private String widgetName;
private double widgetPrice;
Methods represent the actions (verbs) that an object can do, or the messages that an object can respond to.
// declare methods inside the class and outside other methods
// static methods may only access (use) static fields
// non-static methods may access static and non-static (instance) fields
public static int getNumberOfWidgets() {
return numberOfWidgets;
}
private int getWidgetID() {
return WIDGET_ID;
}
private String getWidgetName() {
return widgetName;
}
private double getWidgetPrice() {
return widgetPrice;
}
Constructors are blocks of code that have the same name as the class and they contain code that is used to initialize the values of the instance fields of an object at the time that the object (instance) is created. This is also when memory is allocated to the new object.
static
modifier.this()
// declare constructors inside the class and outside other methods
// and constructors.
public Widget() {
return this("UNKNOWN",0.0);
}
public Widget( String name, double price ) {
numberOfWidgets++; // increment the number of widgets
WIDGET_ID = numberOfWidgets; // set the id number
widgetName = name; // assign the name of this widget
widgetPrice = price; // assign the price of this widget
}
This example correctly places all of the above pieces into a few classes that can be used together to create Widgets and then print them out. Widgets could be used in an inventory program or other.