Tech on YouTube

GeorgiaTechComputerScience

LNK2LRN™2009/010

January 15 to February 10

AP Computer Science A

Ch.9: Creating Objects in Java.

      [EV1 Concept Car Dash]

 

 

 

 

Weekly Plans and Assignments:

1. Friday(01/15): Intro. to Ch.9 - Creating Objects in Java. Start with

Prog09_1 A Car as an Object. HW: Finish Prog09_1 A Car as an Object

and turn-in the result.

2. Monday(01/18): No School - Dr. Martin Luther King Day. HW: View

PowerPoint Presentation on Contributions of African-American Physicists

and Engineers. Click HERE.

3. Tuesday(01/19): Continue with Prog09_1 A Car as an Object.

Adding Attributes. HW: Finish Prog09_1 A Car as an Object and turn-in

the result.

4. Wednesday(01/20): Prog 09_2 An Atom as an Object. Deciding on

its Attributes. HW: Finish Prog09_2 An Atom as an Object and turn-in

the result.

5. Thursday(01/21): Prog 09_3 A Planet as an Object. HW: Finish

Prog 09_3 A Planet as an Object and turn-in the result.

6. Friday(01/22): Prog 09_4 Polygon as an Object. HW: Finish

Prog 09_4 Polygon as an Object and turn-in the result.

7. Monday(01/25): (Student Project) Prog 09_5 Creating Your Own

Object. HW: Finish Prog 09_5 Creating Your Own Object and turn-in

the result.

8. Tuesday(01/26): Continue with Project Prog09_5 Creating Your Own

Object by adding more attributes. HW: Finish Prog 09_5 Creating Your

Own Object and turn-in the result.

9. Wednesday(01/27): Continue with Project Prog09_5 Creating Your

Own Object by adding more attributes. HW: Finish Prog 09_5 Creating

Your Own Object and turn-in the result.

10. Thursday(01/28): Prog 09_6 DVD Store as an Object. To see a

sample program to expand on, click HERE1 for the main and HERE2 for

the class (Extra Credit for the mostcreative improvements).

HW: Finish Prog 09_6 DVD Store as an Object and turn-in the result.

11. Friday(01/29): Continue with Prog 09_6 DVD Store as an Object by

adding more attributes. HW: Finish Prog 09_6 DVD Store as an Object

and turn-in the result.

12. Monday(02/01): Last Day for Prog 09_6 DVD Store as an Object.

HW: Finish Prog 09_6 DVD Store as an Object and turn-in the result.

13. Tuesday(02/02): Prog09_7 Athletes as Objects. Computerized

Player Evaluation. HW: Finish Prog 09_7 Athletes as Objects and

turn-in the result.

14. Wednesday(02/03): Continue with Prog09_7 Athletes as Objects.

Computerized Player Evaluation by adding attributes. HW: Finish

Prog 09_7 Athletes as Objects and turn-in the result.

15. Thursday(02/04): Last Day for Prog09_7 Athletes as Objects.

Computerized Player Evaluation. HW: Finish Prog 09_7 Athletes as

Objects and turn-in the result.

16. Friday(02/05): REVIEW I Ch.9 - Java Objects. HW: Finish

Review Handout.

17. Monday(02/08): AP Exam Review from AP Central. HW: Complete

Review Handout.

18. Tuesday(02/09): Review II for Ch.9. HW: Complete Review

Handout.

19. Wednesday(02/10): TEST on Ch.9. HW: Go to website for notes on

Ch.10 - Graphics in Java.

Very Important: If you have any questions or were absent from class,

see me before school (8:00 - 8:30 AM), during Lunch, or after school.

Best to send an email to rpersin@fau.edu.

 

Website Notes - Ch.9: Creating Objects in Java.

Inheritance

This chapter also discusses the syntax and semantics of inheritance using

some simple examples. The next chapter continues the discussion using

larger examples.

All object oriented languages have a feature called inheritance.

Inheritance enables you to define a new class based upon an existing class.

The new class is similar to the existing class, but has additional member

variables and methods. This makes programming easier because you can

build upon an existing class instead of starting out from scratch.

Inheritance (and other features of object oriented languages) is responsible

for the enormous success of modern software. Programmers are able to build

upon previous work and continuously improve and upgrade software.

For example, in programming graphical user interfaces, the visual components

 are customized by using inheritance with basic components. You don't need

to write the code for the basic components.

Related Topics:

  • Single Inheritance
  • IS-A Relationship
  • Class Hierarchies
  • Syntax of Java Inheritance
  • The super Reference
  • Method Overriding

If you have the source code for a class, you could copy the code and change it

to do what you wanted. With pre-object-oriented languages this was your only

choice. There are at least two problems with this:

(i) keeping things organized,

and (ii) the need to understand the original code.

(i) Say that you have several dozen classes and that your program needs

several dozen more classes based on the original ones. You will end up with

many dozens of source files which are all based on other source files in

variousways. Without careful planning you will end up with an unorganized,

hard-to-follow, buggy mess.

(ii) Say that you have a complicated class that basically does what you want,

but you need a small addition. If edit the source code, even to make a small

change, you risk breaking something. So you must study the original code to

besure that your changes are correct. This may not be easy.

The automatic inheritance mechanism of Java greatly relieves both of these

problems.

Single Inheritance

The class that is used to define a new class is called a parent class (or

superclass or base class.) The class based on the parent class is called a

child class(or subclass or derived class.)

In Java, (unlike with humans) children inherit characteristics from just one

parent. This is called single inheritance. Some languages allow a child to

inherit from more than one parent. This is called multiple inheritance. With

multiple inheritance, it is sometimes hard to tell which parent contributed

what characteristics to the child (as with humans.) Java avoids these

problems by using single inheritance.

Interchangeable Phrases

There are three sets of phrases for describing inheritance relationships:

parent/child, base class/derived class, superclass/subclass. Programmers

use all three sets interchangebly. The picture shows these equivalent pairs.

A parent class is a blueprint that is followed when an object is constructed.

A child class of the parent is another blueprint (that looks much like the

original), but with added features. The child class is used to construct

objects that look like the parent's objects, but with added features.

In a hierarchy, each class has at most one parent but might have several

children classes. The class at the top of the hierarchy has no parent. This

class is called the root of the hierarchy.

A class may be the parent for a child class and may be a child of another

class. Just as with human relationships, a person is a child of some

humans and a parent to others.

The syntax for deriving a child class from a parent class is:

class childClass extends parentClass
{
   // new characteristics of the child class go here

DVD Store Example

Programming in Java consists mostly of creating class hierarchies and

instantiating objects from them. The Java Development Kit gives you a

rich collection of base classes that you can extend to do your work.

Here is a program that uses a class DVD to represent those available at

a rental store. Inheritance is not explicitly used in this program (so far).



 

class DVD

{ String title; // name of the item

int length; // number of minutes

boolean avail; // is the DVD in the store?

// constructor

public DVD( String ttl )

{title = ttl; length = 90; avail = true;

}

// constructor

public DVD( String ttl, int lngth )

{title = ttl; length = lngth; avail = true;

}

public void show()

{System.out.println( title + ", " + length + " min. available:" + avail );

}

}

public class DVDStore

{public static void main ( String args[] )

{DVD item1 = new DVD("Jaws", 120 );

DVD item2 = new DVD("Star Wars" );

item1.show();

item2.show();

}

}

 

Using Inheritance

The DVD class has basic information in it, and would be OK for documentaries

and instructional tapes. But movies need more information. Let us make a

class that is similar to DVD, but has the name of the director and a rating.

 

class Movie extends DVD

{

String director; // name of the director

String rating; // G, PG, R, or X

// constructor

public Movie( String ttl, int lngth, String dir, String rtng )

{super( ttl, lngth ); // use the super class's constructor

director = dir; rating = rtng; // initialize what's new to Movie

}

}

The class Movie is a subclass of DVD. An object of type Movie has the following

members in it:

member

 

title

inherited from DVD

length

inherited from DVD

avail

inherited from DVD

show()

inherited from DVD

director

defined in Movie

rating

defined in Movie

Both classes are defined: the DVD class can be used to construct objects of

that type, and now the Movie class can be used to construct objects of the

Movie type. The method shown in the superclass DVD is inherited in the

subclass Movie.

 

Using a Super Class's Constructor

The class definition for DVD has a constructor that initializes the member

data of DVD objects. The class Movie has a constructor that initializes the

data of Movie objects. The constructor for class Movie looks like this:

// constructor
public Movie( String ttl, int lngth, String dir, String rtng )
{
  super(ttl, lngth);               // use the super class's constuctor
  director = dir;  rating = rtng;  // initialize the members new to Movie
}

The statement super(ttl, lngth) invokes a constructor of the parent to

initialize some of the data. There are two constructors in the parent.

The one that is invoked is the one that matches the argument list in

super(ttl, lngth). Then the next two statements (on one line) initialize

the members that only Movie has.

Note: When it is used, super() must be the first statement in the

subclass's constructor.

It is called super() because the parent of a class is sometimes called

its superclass.

The Constructor Invoked by super()

A constructor for a child class always starts with an invocation of one

of the constuctors in the parent class. If the parent class has several

constructors then the one which is invoked is determined by matching

argument lists.

For example, we could define a second constructor for Movie that does

not include an argument for length. It starts out by invoking the parent

constructor that does not have an argument for length:

// alternate constructor
public Movie( String ttl, String dir, String rtng )
{
  super( ttl );    // invoke the matching parent class constructor  
  director = dir;  rating = rtng;     // initialize members unique to Movie
}

 

No-argument Constructor

Examine the following proposed constructor for Movie:

// proposed constructor
public Movie( String ttl, int lngth, String dir, String rtng )
{
  title = ttl;       // do what the parent's constuctor does.
  length = lngth; 
  avail = true;
 
  director = dir; rating = rtng;
}

It looks like there is no need to invoke the parent class's constructor

since all variables are initialized in this one. However a constructor

from the parent class is always invoked even if you don't explicity

ask for it. The Java compiler regards the above code as "shorthand"

for this:

// proposed constructor
public Movie( String ttl, int lngth, String dir, String rtng )
{
  super();           // invoke the parent's no-argument constructor
  title = ttl;       // do what the parent's constuctor does.
  length = lngth;  
  avail = true;
  
  director = dir; rating = rtng;
}

As always, super() comes first, even if you don't write it in. If the

parent does not have a no-argument constructor, then using this

"shorthand" causes a syntax error.

In our program the class definition for DVD (the superclass) lacks a

no-argument constructor. The proposed constructor (above) calls for

such a constructor so it would cause a syntax error.

The programmer can write a no-argument constructor for a class. If

the programmer does not write any constructors for a class, then

a no-argument constructor (called the default constructor) is

automatically supplied. If the programmer writes even one constructor

for a class then the default constructor is not supplied.

Instantiating Movie

In the example program, the class definition for DVD includes a

constructor, so the default constructor was not automatically supplied.

So the constructor proposed for Movie causes a syntax error. Let us not

use it. Here is an example program that makes use of the two classes:

class DVDStore
{
  public static void main ( String args[] )
  {
    DVD item1 = new DVD("Microcosmos", 90 );
    Movie     item2 = new Movie("Jaws", 120, "Spielberg", "PG" );
    item1.show();
    item2.show();
  }
}

When you run it, you will get the following output:

Microcosmos, 90 min. available:true
Jaws, 120 min. available:true

The statement item2.show() calls the show() method of item2. This method

was inherited without change from the class DVD. This is what it looks like:

public void show()
{
  System.out.println( title + ", " + length + " min. available:" + avail );
}

It does not mention the new variables that have been added to objects of

type Movie, so nothing new is printed out.

Because the class DVD does not have the variables director nor rating, so

its show() method can't use them.

Overriding Methods

We need a new show() method in the class Movie:

// added to class Movie
public void show()
{
  System.out.println( title + ", " + length + " min. available:" + avail );
  System.out.println( "dir: " + director + "  " + rating );  
}

Now, even though the parent has a show() method the new definition of show()

in the child class will override the parent's version.

A child's method overrides a parent's method when it has the same signature

 as a parent method. Now the parent has its method, and the child has its own

method with the same signature. (Remember that the signature of a method is

the name of the method and its parameter list.)

An object of the parent type will include the method given in the parent's

definition. An object of the child type will include the method given in the

child's definition.

With the change in the class Movie the following program will print out the full

information for both items.

class DVDStore
{
  public static void main ( String args[] )
  {
    DVD item1 = new DVD("Microcosmos", 90 );
    Movie     item2 = new Movie("Jaws", 120, "Spielberg", "PG" );
    item1.show();
    item2.show();
  }
}

The line item1.show() calls the show() method defined in DVD, and the line

item2.show() calls the show() method defined in Movie.

Microcosmos, 90 min. available:true
Jaws, 120 min. available:true
dir: Spielberg PG

Yes, it looks like we wrote the same code twice.

 

Using super in a Child's Method

Sometimes (as in the example) you want a child class to have its own

method, but that method includes everything the parent's method does.

You can use the super reference in this situation. For example, here is

DVD's method:

public void show()
{
  System.out.println( title + ", " + length + " min. available:" + avail );
}

Here is Movie's method without using super:

public void show()
{
  System.out.println( title + ", " + length + " min. available:" + avail );
  System.out.println( "dir: " + director + "  " + rating );  
}

Movie's method would better be written using super:

public void show()
{
  super.show();
  System.out.println( "dir: " + director + "  " + rating );  
}

Unlike the case when super is used in a constructor, inside a method

super does not have to be used in the first statement.

  1. You should not have to write the same code more than once.
  2. Changes made to method in parent class are inherited by child class.

 

Music DVD Class

So far the DVD rental application has two classes: DVD and Movie. Say that

you wanted to create a new class, MusicDVD that will be like DVD but will

have two new instance variables: artist (the name of the performer) and

category ("R&B", "Pop", "Classical", "Other" ). Both of these will be Strings.

The MusicDVD class will need its own constructor and its own show() method.

Here is the parent class:

class DVD
{  String  title;    // name of the item
  int     length;   // number of minutes
  boolean avail;    // is the tape in the store?

  // constructor
  public DVD( String ttl, int lngth )
  {    title = ttl; length = lngth; avail = true; 
  }

  public void show()
  {    System.out.println( title + ", " + length + " min. available:" + avail );
  }  
}

 

Adding a Constructor

The MusicDVD class is a subclass of DVD. A skeleton of the definition is below.

The Movie class is not shown, but is also a subclass of DVD. Remember that

a class can have several subclasses.

class DVD
{  String  title;    // name of the item
  int     length;   // number of minutes
  boolean avail;    // is the tape in the store?

  // constructor
  public DVD( String ttl, int lngth )
  {    title = ttl; length = lngth; avail = true; 
  }

  public void show()
  {    System.out.println( title + ", " + length + " min. available:" + avail );
  }
  
}

class MusicDVD extends DVD
{  String artist;
  String category;

  // The constructor will go here

  // The show() method will go here
}

MusicDVD inherits title, length, and avail from its parent and adds artist and

category.

Writing the Constructor

Notice that MusicDVD inherits only from its parent DVD. It does not inherit

anything from its sibling class Movie. Here is the definition so far:

class DVD
{  String  title;    // name of the item
  int     length;   // number of minutes
  boolean avail;    // is the tape in the store?

  // constructor
  public DVD( String ttl, int lngth )
  {    title = ttl; length = lngth; avail = true; 
  }

  public void show()
  {    System.out.println( title + ", " + length + " min. available:" + avail );
  }
  
}

class MusicDVD extends DVD
{  String artist;
  String category;

  // The constructor will go here

  // The show() method will go here

}

We need a constructor for MusicDVD. Use four parameters for title, length,

artist and category. Initialize avail to true.

A whole new show()

Here are the class definitions so far:

class DVD
{  String  title;    // name of the item
  int     length;   // number of minutes
  boolean avail;    // is the tape in the store?

  // constructor
  public DVD( String ttl, int lngth )
  {    title = ttl; length = lngth; avail = true; 
  }

  public void show()
  {    System.out.println( title + ", " + length + " min. available:" + avail );
  }
  }

class MusicDVD extends DVD
{  String artist;
  String category;
  
  // constructor
  public MusicDVD ( String ttl, int len, String art, String cat )
  {    super( ttl, len );
    artist   = art;
    category = cat;
  }

  // The show() method will go here

}

Remember that the super reference (if it is used) must be in the first

statement of the constructor.

To finish the MusicDVD class, write a show() method for it. Use a super

reference to do the things already done by the parent class.

Complete MusicDVD Class

The show() method for MusicDVD can use super.show() where ever it needs to.

It is the first statement (below) because that is where it makes the most

sense.

class DVD
{
  // stuff ommitted here
  public void show()
  {    System.out.println( title + ", " + length + " min. available:" + avail );
  }
  
}

class MusicDVD extends DVD
{  String artist;
  String category;
 
  // constructor
  public MusicDVD ( String ttl, int len, String art, String cat )
  {    super( ttl, len );
    artist   = art;
    category = cat;
  }
  
  public void show()
  {    super.show();
    System.out.println( "artist:" + artist + " style: " + category );
  }
}

All DVD tapes will have a rental price, so the fixes should be made to the

parent class DVD. A new variable rent should be added to the parent class.

Then modify its constructor and its show() method. The two child classes

will inherit these changes. Fixing the parent class fixes all of its children.

The Object Class

Remember the rule: every constructor starts out with a super() constructor.

If you don't explicitly put it in, then the Java compiler automatically puts

it in for you. Now look at the definition of DVD:

class DVD
{  String  title;    // name of the item
  int     length;   // number of minutes
  boolean avail;    // is the tape in the store?

  // constructor
  public DVD( String ttl, int lngth )
  {    title = ttl; length = lngth; avail = true; 
  }

  public void show()
  {    System.out.println( title + ", " + length + " min. available:" + avail );
  } 
}

According to the rule, the compiler automatically does this:

  // constructor
  public DVD( String ttl, int lngth )
  {    super();     // use the super class's constuctor
    title = ttl; length = lngth; avail = true; 
  }

All classes have a parent class (a super class) except one. The class at

the top of the Java class hierarchy is called Object. If a class definition

does not specify a parent class then it automatically has Object as a

parent class. The compiler automatically assumes, for example:

class DVD extends Object
{
. . .
}

If you define a class that does not explicitly extend another class, then

it automatically extends Object. If you define the class so that it extends

a class other than Object, then that class either extends another class or

extends Object. Now that class in turn must either extend another class

or extend Object. There is no way to end the chain except by (ultimately)

extending Object.

You might cleverly try to have class A extend class B, and have class B

extend class A. But this (and other loops) is not allowed.

Ultimately, every Java object inherits its object-like behavior from the

class Object. When an object is constructed a chain of constructors is

invoked starting with the one in Object and ending with the one in the

requested class. The fundamental parts of the object are put together

by the constructor in Object, then additional parts are added down the

chain until the requested class is reached.

Construction starts with the constructor in Object because each

constructor (except Object's constructor) starts by invoking its super()

constructor (with or without arguments).

 

 

 

animated open door gifThe Vault  

CH.1_Introduction to Computer Science  

CH.2_Java Basics 

CH.3_Char, Loop, Selection Statements 

Ch.4  Java Char and String Classes.

CH.5_Using Arrays in Java

CH.6  File IO in Java

CH.7  Java Classes and Methods