User:Ervinn/Classes, Objects and Types

From Wikibooks, open books for an open world
Jump to: navigation, search

Test same time edit 1


A class is an abstract data type that encapsulates state and behavior. In more concrete terms a class has methods and attributes.


An object is created based on its class. You can consider a class as a blueprint, template, or a description how to create an object. You can view the class as a recipe for creating an object. The object is the result of implementing the recipe, the actual meal.


The type of an object is what the outside world will see. The type is the interface to the external objects. The type of an object is a list of messages/operations, the external world can perform on the object. The object reference variable type determines what operations can be performed on the object it holds, even if the object could perform more.

So an object reference:

  • has a type, that determines the operations that can be performed, and
  • has/point to the object (that was created by a particular class) who will do the extual operation
Type objRef = new ClassName();

The above assignment is valid only if the operations declared by the Type, ClassName can perform. So they must be related to each other.

The Type can either be a class, or an interface.

  • If Type is a class: ClassName must be inherited from it
  • If Type is an interface: ClassName must implemented it.

Type Casting[edit]

Type casting means that we assign the same object reference to different Type variable, and by doing that we change the object interface to the outside world. But the same rule applies regardless, that is all operations declared by the Type, the object must be able to perform.

We can go three ways:

  • up casting: going up in the inheritence tree, until we reach the Object
  • up casting: to an interface the class implements
  • down casting: until we reach the class the object was created from