wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes inheritance homework assignment - im stuck Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "inheritance homework assignment - im stuck" Watch "inheritance homework assignment - im stuck" New topic
Author

inheritance homework assignment - im stuck

Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
Greetings all, this is my first time here.

Since the class I am taking is considered an intro / beginning java class, I figure this forum would be appropiate for my question. Please note that I am not looking for somebody to do my work for me, rather I am looking for some pointers as I seem to be lacking the understanding of some concepts that make it possible for me to complete my home work assignment.

My assignment is;

------------
Use inheritance to display a student record

Operation
�The user enters a college student�s identification number followed by the major and GPA.

�The application creates a college student object and displays the object to the screen.


Specifications
�First, create a class that defines a student. This class should contain at least two instance variables for identification number and GPA. It should also contain two constructors�a default one and one that accepts two values for the instance variables. In addition to set and get methods, the class should override the toString method from the Object class.

�Next, create a class that defines a college student. To do this, the class should inherit the above class. In addition to the inherited instance variables, this class should contain at least one more instance variable that defines the college student�s major. This class should also contain a default constructor and one that accepts three values for the instance variables. The first statement in this constructor should call a constructor in the superclass. This class should also override the toString method.

�Code a driver class that carries out the operation of the project.

�Assume valid data is entered.

------------

So far this is what I have;

For the first item (I did not do the overriding yet) in the specs;

public class Student
{ // begin class

private String ID; // instance variable
private String GPA; // instance variable

public Student() // default constructor
{
ID = "";
GPA = "";
}

public Student(String studentID, String studentGPA) // constructor for the two instance variables
{
ID = studentID;
GPA = studentGPA;
}

public void setID(String studentID) // method
{
ID = studentID;
}

public void setGPA(String studentGPA)
{
GPA = studentGPA;
}

public String getID()
{
return ID;
}

public String getGPA()
{
return GPA;
}

} // end class

For the second spec item (again without the override);

public class CollegeStudent extends Student
{
private String major;

public CollegeStudent () // default constructor
{
major = "";
}

public CollegeStudent(String studentID, String studentGPA, String studentMajor) // constructor
{
super(studentID, studentGPA);
major = studentMajor;
}

public void setmajor(String studentMajor) // method
{
major = studentMajor;
}

public String getmajor()
{
return major;
}
}

and then for my driver class;

import javax.swing.JOptionPane;

public class StudentRecordApp
{
public static void main(String[] args)
{
String choice = "";
while(!(choice.equalsIgnoreCase("x")))
{

String studentID = JOptionPane.showInputDialog(
"Enter college student's ID:");
//String studentMajor = JOptionPane.showInputDialog(
// "Enter college student's major:");
String studentGPA = JOptionPane.showInputDialog(
"Enter college student's GPA:");

Student student = new Student(studentID, studentGPA);

String result = "Student number: " + student.getID() + "\n"
+ "GPA: " + student.getGPA() + "\n"
//+ "Major: " + CollegeStudent.getmajor() + "\n\n "
+ "Press Enter to continue or 'x' to exit.";
choice = JOptionPane.showInputDialog(result);
} // end while
System.exit(0);
} // end main
} // end class


-----------

My questions;

How does this look so far (in regards to the specs)?

-Since the CollegeStudent class is a subclass it inherits the variables of the superclass (Student). Do I keep the return statements in the superclass, or do the returns in the subclass? Does that question even make sense, cause I just managed to confuse myself?

-I dont understand the requirement of overriding at all.

Thanks!


-Giles
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

this looks like a good start. you may want to store the GPA as a float, although this would require you to do some conversions, so maybe not.

either you or I have missed the "override the toString method" part of the specs.

you question about "returns" - i think everything is fine.

overriding just means "a certain method with a certain signiature already exists in a superclass, but i'm going to write a special one for my subclass".

Your Student class automatically derives from the Object class. the Object class has a "toString()" method, that really isn't very useful, in your case. so, you need to write a "toString() method in your Student class. It should return a String (that's kind of obvious), and take no parameters. For this assignement, i'd just build a string that say something like "Student 12345 has a GPA of 3.75.", then return that string.

you can then override THAT toString method in your CollegeStudent class. you can call super.toString() and get a string, then append " Their major is Java.", and return THAT string to the driver program.

does that help?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
thanks for the reply Fred. I have enclosed my responses below.

Originally posted by fred rosenberger:
this looks like a good start. you may want to store the GPA as a float, although this would require you to do some conversions, so maybe not.

one of the givens in the spec. is to assume all data that has been entered is valid, which is why i went with a string. i hope that is ok.


either you or I have missed the "override the toString method" part of the specs.
i wanted to get everything else done first before the override as I dont understand this concept.


overriding just means "a certain method with a certain signiature already exists in a superclass, but i'm going to write a special one for my subclass".
hmmm... im still trying to picture this in my mind, but I cant...


Your Student class automatically derives from the Object class.
what Object class? I thought objects couldnt exist with out classes and so then objects derive from classes?


the Object class has a "toString()" method, that really isn't very useful, in your case.
by object class do you mean driver class?


so, you need to write a "toString() method in your Student class. It should return a String (that's kind of obvious), and take no parameters. For this assignement, i'd just build a string that say something like "Student 12345 has a GPA of 3.75.", then return that string.

you can then override THAT toString method in your CollegeStudent class. you can call super.toString() and get a string, then append " Their major is Java.", and return THAT string to the driver program.

does that help?
it does, but now i have more questions. LOL. i think im missing some key concepts.
[ June 22, 2004: Message edited by: Giles Harney ]
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
(sorry for the bold text in my reply. apparently one can not edit their own posts to fix any mistakes.)

edit - now it seems i am able to edit it.
[ June 22, 2004: Message edited by: Giles Harney ]
Anthony Watson
Ranch Hand

Joined: Sep 25, 2003
Posts: 327
You can edit your post by clicking on the icon that looks like a paper and pencil. It is located at the top of your posts.
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
ok, let me break down step by step;

�First, create a class that defines a student. This class should contain at least two instance variables for identification number and GPA. It should also contain two constructors�a default one and one that accepts two values for the instance variables.

does this code satisfy the above requirement;

public class Student
{ // begin class

private String ID; // instance variable
private String GPA; // instance variable

public Student() // default constructor
{
ID = "";
GPA = "";
}


???
Eric Fletcher
Ranch Hand

Joined: Oct 26, 2000
Posts: 188
Originally posted by Giles Harney:

does this code satisfy the above requirement;

public class Student
{ // begin class

private String ID; // instance variable
private String GPA; // instance variable

public Student() // default constructor
{
ID = "";
GPA = "";
}


???


Hi Giles,

It almost, but not quite, satisfies the requirement. You have defined the two instance variables, and given a default, or no-argument(hint, hint), constructor. The requirement missing is the second constructor, the one that is supposed to take the two values. A constructor is a special type of method that returns a new instance of it's class, so, how do we get information into a method? We pass in arguments, and a constructor is no different. So you need to create another constructor that has two arguments, one to pass in an ID, and one to pass in the GPA, then set the instance variables to the values passed in.

HTH,
Eric


My theory of evolution is that Darwin was adopted. - Steven Wright
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
Originally posted by Eric Fletcher:

The requirement missing is the second constructor, the one that is supposed to take the two values. HTH,
Eric


Hello Eric,

Thanks for the reply.

In my cutting and pasting I forgot to include the second constructor, here is what I should of posted;

public class Student
{ // begin class

private String ID; // instance variable
private String GPA; // instance variable

public Student() // default constructor
{
ID = "";
GPA = "";
}

public Student(String studentID, String studentGPA) // constructor for the two instance variables
{
ID = studentID;
GPA = studentGPA;
}

----

is that better?

also, I did a forum search for default constructor and some of the posts have the default (no-arg?) constructor coded as;

public ClassName(){}

can I use

public Student(){}

in place of the default constructor that I used?

thanks!

-Giles
[ June 22, 2004: Message edited by: Giles Harney ]
Darin Niard
Ranch Hand

Joined: Jun 08, 2004
Posts: 118
Originally posted by Giles Harney:

can I use

public Student(){}

in place of the default constructor that I used?


As long as you instantiate the String variables. You shouldn't have getWhatever returning null.

BTW, I won't be surprised if you get points off for using a String to represent someones GPA...

Originally posted by Giles Harney:

one of the givens in the spec. is to assume all data that has been entered is valid, which is why i went with a string. i hope that is ok.


They only mean that you do not have to do any error checking on the data that is passed in. For example, you do not have to check to see if the GPA provided is between 0 and 4.
[ June 22, 2004: Message edited by: Darin Niard ]
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

Java, as you know, is an OO language. that means that most things (primitives being the exception) are objects (note: little o). You can write your own objects, derive from objects you write, etc. You seem to have this concept.

Sun, in their infinite wisdome, created a bunch of objects (again, little o) for us to use. Strings. Arrays. Hashtables. Don't worry if you don't know all of them - nobody really does. That's what the documentation is for.

But - and this is key - Sun created one special object. It is the grand-daddy-super-cheif head object. Sun decided to call it the Object (note: capital-O) class. Here's the kicker - EVERY OBJECT IN JAVA, WHETHER WRITTEN BY SUN OR CREATED BY YOU DERIVES FROM THAT CLASS. You don't even have to tell the compiler that your Student class extends Object. the compiler knows - it's hardwired in. You can't avoid it.

If you declare class myObjectA extends myObjectB; then myObjectB extends myObject C; and on and on and on, the topmost one will derive from Object. Therefore, every class down the heirarchy chain will ALSO be derived from Object.

I'm only stressing that because it's important.

so to recap - all classes, created by you, by your friend, or by Sun, derive directly or through a heirachy chain from the Object class.

Now, to answer one of your questions. the Object class has some methods pre-written for you. if you go here, you can see some of them. Many don't do anything useful, but they garantee you can ALWAYS call these methods on EVERYTHING (since everything is one of these).

so, with your Student class, you already have a toString() method, curtesy of Sun's Object class. try it - do a

System.out.println(student.toString());

in your driver, and you'll get something - i think it's a memory location. it's not very helpful. What you need to do is override that method in your class. you need to write a method that is called the same thing, and that takes the same type/order parameters (in this case, none). so, you need, in your Student class, a method something like

String toString(){
String returnString = //some useful, relavant string built here
return returnString;
}

(note: this code may not be perfect - it's early and i haven't found the coffee machine yet).

once you have this method in your Student class, you can say you have "overridden" the Object toString() method.

Notice that your CollegeStudent class will get your new toString() method - hooray for inheritance!!! that saves you some work... sort of.

now, you need to override Student's toString method, since the CollegeStudents toString() method should probably be a little different. but maybe not too different. maybe it'd be nice to use the string you'd get from the Student class, and just add something to it. it'd be nice if you could call your superclass' method... and you can, using the "super" keyword. in CollegeStudent, you'd have something like

String toString(){
String temp = super.toString();
temp = temp + //whatever else you need to add to it
return temp;
}

before anybody else yells at me, you should know this is actually pretty bad code - you never want to really add strings like this - it's legal, it'll work, but it'll eat memory and kill your cpu if you do it a lot. but for this app, it should work fine.

So i've written a lot (probably to much). ask more questions - i usually check here a lot during the day Central time. or others will always help too!!!

good luck!
Jack Lord
Greenhorn

Joined: Jun 04, 2004
Posts: 11
Originally posted by fred rosenberger:

String toString(){
String temp = super.toString();
temp = temp + //whatever else you need to add to it
return temp;
}

before anybody else yells at me, you should know this is actually pretty bad code - you never want to really add strings like this - it's legal, it'll work, but it'll eat memory and kill your cpu if you do it a lot. but for this app, it should work fine.


I don't want to hijack the thread (well maybe just a little ) but can I ask why this is bad code? If I add "one" and " two" strings together do I end up up with three strings in memory: "one", "two" and "one two", even if they're no longer all referenced by some variable? Or is something else causing memory to get eaten up?

Sorry if that makes no sense but that is how I've been adding strings together in my programs and now I'm kind of concerned, especially as I like to know what is going on at a low level.
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
thank you to Fred, Eric and Darin for your replies.

I have thoroughly confused myself now. i think i need to go back and relearn what a class is. i just cant picture any of this in my mind.

apparently the java for dummies book i have is not dumbed down enough for me. i need to go find the java for idiots such as myself book.

sigh.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

a Class is a blueprint for how to make something, what that something has, and what it does.

an object (little o) is a specific instance. i can use the same blueprint to make 30 things - each can do the same stuff, but has different values.

in other words, i can define a Person class that has a name, address, age and phone number. I have methods that get or set each of these variables. I also have a method that prints out a nice description of a person and what all those variables are.

I then create several Person objects. Bob, Pete and Susan. Each has a unique name, etc. stored somewhere. and for ANY of them, i can call the various methods defined in my Class definition, since they are all of type Person.

You can then use something called inheritance by using the 'extends' keyword. i can make a new class definition called EmployedPerson that extends Person (the Person class is called the parent, or the superclass of EmployedPerson, which is the child class or derived class). if ALL i write is

these classes are identical. i get all the member variables, all the methods, constructors, etc. free for nothing. that's not very useful. so i add a few things...


so, in my new class i only wrote 2 methods (maybe a new constructor or 2), but it has 10 (2 i wrote in this class, 8 it inherited). that's pretty cool. There's more than just this, but i'm afraid of overwhelming you (although it may be too late).

One thing i want to emphasize is that if you don't explicitly state that your class extends something, the Java compiler automatically makes it extend the Object class (note the capital "O"). Sun created this special class that EVEYRTHING derives from, either directly or through it's parent's parent's parent...
[ June 24, 2004: Message edited by: fred rosenberger ]
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

Originally posted by Jack Lord:


I don't want to hijack the thread (well maybe just a little ) but can I ask why this is bad code? If I add "one" and " two" strings together do I end up up with three strings in memory: "one", "two" and "one two", even if they're no longer all referenced by some variable? Or is something else causing memory to get eaten up?



I always have a hard time explaining exactly what goes on (which probably means i don't fully understand the details myself). But basically, there are two types of strings - String literals, and String variables. a literal is anyplace in your code where you have quotes. Literal strings are put in a string pool somewhere. if you have "one" in your code in 30 places, it's only stored once in the pool.

if you write

myString refers to that literal.

However, if you have


then the literal is created, AND a String object is created with the value "one" - in other words, there are now two hunks of memory being used.

i'm not sure what happens if you add two or more literals together - if the compiler can optimize them into one long string in the pool or not.

but when you start using String variables, all kinds of things happen.



first, you get a copy of myString. then you add something to it - which requires the creation of a new string. then you add something to that, which creates a new string, and then you add something to that, which creates a new string.

This seemingly innocuous statement is requireing the creation of 4 extra strings, and leaves the old one around. they're all sitting there in memory, until the garbage collector gets fired up and cleans them (note that string literals never get cleaned up). you're just creating lots of extra work for the JVM and the GC. you're better off using a StringBuffer, which can resize itself as needed.

And, for small applications, like most of the ones you write in school, it won't make one iota of difference. but if you writing something that will register thousands of college kids, and the app will be running for hours (days... weeks) at a time, you would really want to avoid these performance/memory hits.

that's at least my understanding - it may not be perfect or 100%, but it should help.
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
going back to my original class code and driver code; (please see top of thread)

from the class code
-----

public Student(String studentID, String studentGPA) // constructor for the two instance variables
{
ID = studentID;
GPA = studentGPA;
}

why am I setting a new var (ID) to an existing one that was declared in the driver class?

why couldnt i just use the existing var?
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Originally posted by fred rosenberger:


first, you get a copy of myString. then you add something to it - which requires the creation of a new string. then you add something to that, which creates a new string, and then you add something to that, which creates a new string.

This seemingly innocuous statement is requireing the creation of 4 extra strings, and leaves the old one around.

I have an old printing of "The Java Programming Language, Second Edition". It says that the compiler uses a StringBuffer object to build strings from expressions, creating the final String only when necessary.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

I think what you are asking is "if i already have a studentID, why to i have to create a new variable (ID)in my class. why can't i just use the existing one?"

Imagine you are registering students at a college. you probably have a loop to keep inputting the data. so you are using that same studentID variable over and over and over. once you have all the data for one actual person, you can create a Student object. then you'll create another one, and another one...

Each new Student object you create has to remember it's own student's id number. So, you get the input in your studentID string, then create this object to represent an actual person. so you set that objects variable to be what the temp variables are.

when you then get the NEXT studentID, the ID in your student object will still point to the correct info. your studentID will now refer to a new string, with new data. this will then be used to create the second Student object.

keep asking questions... it's the best way to learn.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

Originally posted by Irina Goble:

I have an old printing of "The Java Programming Language, Second Edition". It says that the compiler uses a StringBuffer object to build strings from expressions, creating the final String only when necessary.


Ok, i'm not surprised i am wrong. All i know is that every developer that i respect has always said this is a bad thing to do. it's possible SUN has optimized away a lot of the badness.
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Giles,

You might want to call the superclass's default constractor from CollegeStrudent's default constractor.



Just in case if something changes in Student()
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
Originally posted by fred rosenberger:

keep asking questions... it's the best way to learn.


dont say i didnt warn you.

ok, if i were to step through this program in the order that it would be executed, would the following be correct;

-prompt for input and assign to a variable

-call the class file (student) and pass to it studentID and studentGPA
-build each object (instance) with 2 instance vars- id & gpa
-assign studentID and studentGPA to id and gpa respectively
-use a method to perform some action on the data (in this case it seems redundant)
-go back to driver class
-display results by calling the getID and getGPA methods in the student class file.


?

thanks!
-Giles
KR Campbell
Ranch Hand

Joined: Mar 26, 2004
Posts: 124
Originally posted by fred rosenberger:


Ok, i'm not surprised i am wrong. All i know is that every developer that i respect has always said this is a bad thing to do. it's possible SUN has optimized away a lot of the badness.


No, if you are wrong, so is Joshua Bloch (and I wouldn't bet a cent on that). This is item 33 in 'Effective Java'. He says that it takes quadratic time on n strings to concatenate. The reason is because String objects are immutable and consequently both the original string and the newly added one must be copied for each concatenation.

Regards,
Ken
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

Originally posted by Giles Harney:


ok, if i were to step through this program in the order that it would be executed, would the following be correct;

-prompt for input and assign to a variable

-call the class file (student) and pass to it studentID and studentGPA
-build each object (instance) with 2 instance vars- id & gpa
-assign studentID and studentGPA to id and gpa respectively
-use a method to perform some action on the data (in this case it seems redundant)
-go back to driver class
-display results by calling the getID and getGPA methods in the student class file.


I'd proably word it differently. try and abstract some of this stuff out. for starters, just think about your driver class...

- prompt for input and store data in temp variables.
- make a Student object by calling it's contructor, passing in the relavent data (right now we don't care HOW that happens)
- display results using getID and getGPA
- you can also display something by calling the toString() method

ok, now lets think about the Student class
- one constructor takes NO arguments. i must intialize the two string i have to "".
- one constructor hands me two string that i'll need to remember. so, i'll set my member variables (ID and GPA) to remember what paremeters i was given (studentID and studentGPA) (this is all done in the constructor)
- i need to be able to tell the world what my ID is - hence the getID() method that returns a string
- i need to be able to tell the world what my GPA is - hence the getGPA method.
- i need to let somebody CHANGE my GPA - hence setGPA
- i need to let somebody CHANGE my ID - hence setID

your driver class really doesn't need to know HOW the Student class does anything. all it needs to know is what to send it, and what it will get back.
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
ok, making progress... ( i still need to figure out overriding the toString method from the Object class)

now i need a subclass that inherits the instance variables from the superclass and also contains an instance variable of its own (major).
This class should also contain a default constructor and one that accepts three values for the instance variables. The first statement in this constructor should call a constructor in the superclass.

my thinking is since the subclass (CollegeStudent) has the values that the superclass (Student) has then i no longer need to create a Student object. I would create a CollegeStudent object. correct?
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
Originally posted by Irina Goble:
Giles,

You might want to call the superclass's default constractor from CollegeStrudent's default constractor.

Just in case if something changes in Student()


Hi Irina,

Thanks for your reply.

Could you please help me understand what you mean by "if something changes in Student()"? An example?

Thanks!
-Giles
Darin Niard
Ranch Hand

Joined: Jun 08, 2004
Posts: 118
Giles, well that depends if you are trying to make a regular Student or a CollegeStudent The main point of inheritance is for code reusability. Classes can share common functionality with eachother, and still be their own individual class.
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
Hi Darin,

Based on the assignment requirements;

-----
Use inheritance to display a student record

Operation
�The user enters a college student�s identification number followed by the major and GPA.

�The application creates a college student object and displays the object to the screen.
-----

I would think I would only need CollegeStudent.
?

Thanks!
-Giles
Darin Niard
Ranch Hand

Joined: Jun 08, 2004
Posts: 118
Originally posted by Giles Harney:

Could you please help me understand what you mean by "if something changes in Student()"? An example?

Currently, your CollegeStudent constructor doesn't contain the ID and GPA variables. This is because the Student's constructor is not being used because you are overwriting it with a new constructor, like any other method. So, you need call the super class' constructor ( super(); ).
[ June 24, 2004: Message edited by: Darin Niard ]
Darin Niard
Ranch Hand

Joined: Jun 08, 2004
Posts: 118
Originally posted by Giles Harney:

I would think I would only need CollegeStudent.

Correct.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11475
    
  16

Darin is right. i might at some point make a Dog class, and then a subclass called Chihuahua with a method that says "Yo Quiro Taco Bell??" (i have two chihuahuas, btw - they're great dogs).

anyway, then, in my driver class, i might want to make a Chihuahua at some point, but i might also want a Dog someplace else (that will get us into a really neat place eventually called polymorphism, but don't worry about that yet).

Could you please help me understand what you mean by "if something changes in Student()"? An example?


what Irina means is this: your CollegeStudent class inherits everthing from Student. you can (and people often would ) say a CollegeStudent IS A Student. now, say you write a constructor for college student that takes 3 parameters - studentID, studentGPA and studentMajor. you need to set all of those. ok, but part of that is very similar to what the 2-arg constructor does in Student. why not just use that code that's already written???

to do this, you call the superclass's constructor with the keyword super. you'd pass the two arguments the superclass needs, then take care of the special stuff for a CollegeStudent...


2 notes:
- you would want to do this for both the no-arg contstructor and the two-arg constructor
- the call to the super MUST be the first thing you do, if you do it at all. it's completly optional, but if it's there, it's the first thing.

calling the superclass constructor does some nice stuff. you don't have to retype your code. and (this is what Irina was saying), if the superclass changes, you get that free in your subclass. Say for example you put some code in the Student class that did error checking - the GPA couldn't be negative, the id had to be 10 characters long... without calling the superclass, you'd have to put this error checking in every derived class. Imagine if you further extended this with a FullTimeCollegeStudent, a PartTimeCollegeStudent, ArtsSciCollegeStudent, EngineeringCollegeStudent... and so on.

code maintenance would be a nightmare. by making the call to the superclasses constructor, any change higher-up is gotten free by the derived classes.
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Giles,

It looks like one of the goals of your assigment is to learn about default constructors that will be generated by a compiler. So for Student the compiler will create :

and for CollegeStudent:

If you write the Student's default constructor as you did before:


you have to call super() in the CollegeStudent's default constructor. Whatever changes can happen with the Student class, try to make your default constructor as good as the compiler's.

I'm new to java and this assigment is very confusing for me. I belive if an object has a state, the state should be consistent during the lifetime of the object. Creating a Student object with no Student Id does not make any sence to me, so if I had to write a default constructor for Student, I would at least make it private. The compiler would not create a default constructor if there is one with agruments. And that is perfect!
Could anyone explain the purpose of the default constructor in this assigment please? (except of learning about how they look).
Michael Tiffany
Greenhorn

Joined: Jun 24, 2004
Posts: 3
To perhaps repeat something that was said before, but add a little clarity: every Class in Java descends from java.lang.Object. Take a look at the API, specifically the java.lang.* package.

The purpose of the default, no-args constructor is... serialization and deserialization. I'll bet that's where your teacher is eventually headed. Serialization is just a fancy way of saying that a particualar instance of a Class can be piped through an output stream so that its state can be saved, or sent to another JVM running somewhere else.

Say for instance that you had a particular instance of Student, with an ID of 12345 and a GPA of 2. If you wanted to save (write) that particular instance of Student to disk, you could do so through Java's serialization mechanism. See java.io.Serializable for details. However, when you wanted to deserialize that particular instance of Student, that is, read it from the disk, the JVM needs a no-args constructor to properly re-instantiate that particular Student.

Hope that helps...

[ June 24, 2004: Message edited by: Michael Tiffany ]
[ June 24, 2004: Message edited by: Michael Tiffany ]
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Sorry for the confusion about the CollegeStudent's default constructor.
The Student's default constructor will be called automatically if there is no explicit super() call as the first statement in CollegeStudent().

Thank you for the explanation about the purpose of the default constructors!
Giles Harney
Greenhorn

Joined: Jun 22, 2004
Posts: 19
thanks to everybody who has replied. i'm sure ill be asking more questions this week.

thanks again!

-Giles
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: inheritance homework assignment - im stuck