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
- A parameter's scope is the
method in which it
- Instance variables have class
scope - they can
be used throughout
the class in which they are declared.
- The scope of a variable
declared inside a
method is the block in
which it is defined. Blocks are delimited by curly braces.
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
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
may put common code in a parent class
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
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.
- String toString(); // returns
representation of the
- boolean equals(Object obj);
// tests whether or
not this object
- Object clone(); // makes a
copy of this object
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
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.