Classes and objects

Specialization

Organisms have evolved organs, specialized structures with particular functions, which interact with each other through relatively narrow-band interfaces. Specializations

A specification for a complete functioning organism includes an arrangement of the organs into a whole and some means of communication among the parts and the whole.

Classes

A class is a kind of template, specifying what all instances of the class share. In Java, class definitions are created with the keyword class followed by an identifier for the class. By convention class names are capitalized, and they usually are defined in a file that consists of the class name with the suffix .java.

A class definition includes one or more of the following:

Each Java class creates a new type, which can be used just like primitive types (int, boolean, etc.) in declaring variables and return types and in casting.

Objects

An object is an instance of some class. Objects are created by calling a constructor for a class (using the keyword new).

If fields are specified in a class definition, they may include variables as well as constants. There are two kinds of variable fields, class variables and instance variables. Class variables have the same value for all instances of a class; they "belong" to the whole class. Class variables are declared with the keyword static.

Instance (or member) variables belong to individual objects rather than to a whole class. For each instance variable defined in a class definition, a separate variable is created for each instance of the class, and different instances may have differ values for these variables. For example, every Critter has an age, an int variable. Since this is an instance variable, each Critter in the program has its own separate age, and when one is changed with an assignment operator, the others are unaffected.

Objects communicate with each other through their instance variables. For example, each Critter has an instance variable for its Brain, a variable with the identifier brain. This allows the Critter to call methods in the Brain. For example, the method step() in Brain is called like this within the Critter class: brain.step();.

A running Java program consists of a set of objects in different states calling their own methods and communicating with other objects that they have access to through their instance variables.

Home

Calendar

Coursework & grading

Assignments

Lecture notes

Other resources


IU home

IU CS home

Contact instructor