Hi new to the forum, so go easy :)

Im very new to Java and im a little stuck...

I have to create a program which uses classes and objects, all of the objects need to be stored in 1 array.

So, i have a super class called Student then 2 subclasses called female and male. So it should look a something like this;

public class Student

student number;
name;

public class Female extends Student(String sGender)
String gender;
gender = sGender;

public class Male extends Student(String sGender)
String gender;
gender = sGender;

Sorry if that looks a little crude. Anyway, my problem is, if i create an array of Student[], then populate it when Females and Males, they lose any unique methods, and every object can only use the methods which are in Student.

I know i can put every method in the super class (student), which are then inherited by the subclasses (Male and Female), but this seems wrong because its taking more code than it should.

Any help would be great.

Possibly the objects are being cast to their superclass.

Possibly the objects are being cast to their superclass.

Thanks for the reply Sean.

Yea funny enough i was just reading up on down casting.

Essentially, i just recreate a new object;

Female f = (Female)Student[0];
f.setGender("Female");
Student(0) = f;

Still a little long winded but it works fine.

I was hoping i could do;

(Female)student[0].setGender("Female");

But, Netbeans did not like that.

There are two solutions;
1.
class Female extends Student
class Male extends Student
abstract class Student
2.
class Female implements Student
class Male implements Student
interface Student

Both methods allows you to write:

public static void main(String args[]) {
        Student[] studentArray = new Student[2];
        studentArray[0] = new Male(22, 6);
        studentArray[1] = new Female(21, true);
    }

classes Male, Female knows own gender
more http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.