Classes and Objects

Remember to read about inheritance in the online Java Tutorial:

Scope of Variables

The scope of a variable or method defines where it can be used in a program.


for(int i = 0; i < n; i++)
   count = count + i;  // i's scope is the for block
System.out.println(i); // Error: i is no longer defined here

An Introduction to Inheritance

Consider a program that involves different types of animals: you write the classes Dog, Cat, and Bird.

As you write these classes, you will notice that they contain some common instance variables:
And some common methods:

Since some of the data and functionality for these classes overlap, we may put common code in a parent class or superclass.

For our program, we may want a parent class called Animal that contains the common instance variables and methods we described above.

Dog, Cat and Bird will be subclasses of the Animal Class, and they will inherit the instance variables and methods in Animal.

The advantage of having the superclass, Animal,  is that we save ourselves the hassle of rewriting code over and over in the subclasses.

Another Example: (in class)

Object: The Superclass of Every Java Class

Every class automatically inherits from class Object - this means that every class extends Object and can use the methods in class Object.

The Object class contains methods that you want every object to have.

Object's methods are very general: here are the most useful ones.

Since these methods are so general, it is a good idea to override them in your own classes. We override a method by providing our own implementation of it.

The instanceof Operator

Syntax: object instanceof ClassName
This operator returns true if the object is an instance of ClassName and false otherwise.

if (x instanceof Square)
   Square xSqr = (Square) x;

Example: Write a Square class which overrides the toString(), equals(), and clone() methods inherited from the Object class. Then write a SquareTest class that tests the Square class.