Sunteți pe pagina 1din 2

Week 8 Notes (CSC120)

Read Chapter 8 of our textbook! Subject: Objects and Classes

A class in Java may be thought of in several slightly different senses:


(a) A class is a kind of thing,
(b) A class is a template that we may use to create objects.
(c) A class is a data type, and as such we may declare object references (4 bytes each) to be
of the type of a given class. The object itself will be allocated space on the heap.
Example: String myName; myName is an object reference that can be null or can hold
the address of a String object on heap space.
An object is an instance of some class. Example, String myName = Billybob; myName is an
object reference to the object that holds Billybob. The object itself resides on heap space.

SEE HANDOUT ABOUT CLASS CALLED HUMAN!

A class definition in Java looks like what is shown below:


public class MyClass {
// Five things go in here:
(a) Class variables/constants (use static in their declaration)
(b) Class methods (use static in their header)
(c) Constructors special methods that (1) have MyClass as their name and (2) have no return
type since they ALWAYS return an object reference to the newly created object. Purpose:
of a constructor see that the instance variables of the newly created object are properly
initialized.
(d) Instance variables (each object will have his own copy of each of these) no static.
(e) Instance methods (methods that we may ask a given object of this type to perform for us
with that object being viewed as the actor doing the method. No static in the header for
these methods.
} // end class definition

Fact: EVERY class we create is in fact a subclass of a class called Object (with a capital O!).
Yes, I see the irony in that. Any class in Java has a single parent class. We can either state the
name of our parent class explicitly, or our parent class is Object if we do not say.
public class Animal { // Child class of Object
versus
public class Mammal extends Animal { // Child class of Animal class.

Relationship of subclasses to parent class: EVERY object of the subclass type IS A object of
the parent class type as well just a specialized version of one.
Meaning of this: instance variables from the parent class are found in all object of the child class
and any method defined by the parent class can be performed by objects of the sub class (some
exceptions to this will be explained later).

A child class can replace an instance method stated in the parent class by giving an alternate
(more appropriate ) version in the subclass this replacement version would have the SAME
header as the one given in the parent class. This is not method overloading, but rather method
overriding.

S-ar putea să vă placă și