simple subclass question

Hi all,

I have a superclass Person and 2 subclasses Male and Female that extend the superclass.

publicclass Person{

// name string

protected String name;

// gender : M or F

protected String gender;

public String getName(){

return name;

}

public String getGender(){

return gender;

}

}// End of class

publicclass Maleextends Person{

public Male(String fullName){

gender ="Male";

name = fullName;

System.out.println("Hello Mr. "+fullName);

}

}// End of class

publicclass Femaleextends Person{

public Female(String fullNname){

gender ="Female";

name = fullName;

System.out.println("Hello Ms. "+fullNname);

}

}// End of class

is this design good or how can it be improved?

is it OK to make gender and name protected vars so that the subclasses can set them directly or is it more appropriat to make a protected set method and not give direct access to these vars?

because I read once that making vars protected was pretty dangerous coding?

Message was edited by:

dfvdfvdfvxfv

Message was edited by:

dfvdfvdfvxfv

[2383 byte] By [dfvdfvdfvxfva] at [2007-11-27 8:17:52]
# 1

Isn't gender just an attribute of a person? How would your design cope with

1) Gender-unknown scenarios

2) People refusing to specify their gender

3) Those third-gender freaks (transvestites with an attitude problem, basically)

4) Sex changes

Actually, I see that gender already is an attribute of your class, so why bother even using inheritance to express it?

You're right about protected members being A Bad Thing ™. It indicates a dependency on a concrete class, for one thing, which is somewhat undesirable. As soon as I see a protected method somewhere in our code, I just know that at some point something entirely unexpected is going to happen, and it nearly always does

(For the record, I don't like subclassing anyway. Your mileage may vary)

georgemca at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

My two krummplenicks :o)

public abstract interface Person implements java.io.Serializable {

public String getPersonName();

public String getPersonGender();

}

public class MaleImpl implements Person {

private String n;

private String g;

public String getPersonName() {

return this.n;

}

...

public MaleImpl(String name, gender) {

this.n = name;

this.g = gender;

}

}

GhostRadioTwoa at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 3

> My two krummplenicks :o)

>

> public abstract interface Person implements

> java.io.Serializable {

>public String getPersonName();

> public String getPersonGender();

> }

>

> public class MaleImpl implements Person {

>private String n;

> private String g;

>

> public String getPersonName() {

>

> return this.n;

>...

>public MaleImpl(String name, gender) {

>this.n = name;

>this.g = gender;

> }

>

But what's your opinion on the use of inheritance to express genders?

georgemca at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 4

Hope this is what you meant.

public abstract interface Person implements java.io.Serializable {

public String getPersonName();

public String getPersonGender();

}

public class PersonImpl implements Person {

private String n;

private String g;

public String getPersonName() {

return this.n;

}

public String getPersonGender() {

return this.g;

}

public PersonImpl(String name, gender) {

this.n = name;

this.g = gender;

}

}

So creation of a male or a female object would be like follows.

Person man = new PersonImpl("John", "Male");

Person woman = new PersonImpl("Jenifer", "Female");

Seems inheritance is not needed for this Male/Female situation.

Kamal-Mettanandaa at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 5

> Hope this is what you meant.

>

> public abstract interface Person implements

> java.io.Serializable {

>

>public String getPersonName();

> public String getPersonGender();

> }

>

> public class PersonImpl implements Person {

>private String n;

> private String g;

>

> public String getPersonName() {

> return this.n;

>

>public String getPersonGender() {

>return this.g;

>

>

>public PersonImpl(String name, gender) {

>this.n = name;

>this.g = gender;

> }

>

>

>

> So creation of a male or a female object would be

> like follows.

>

> > Person man = new PersonImpl("John", "Male");

> Person woman = new PersonImpl("Jenifer", "Female");

>

>

> Seems inheritance is not needed for this Male/Female

> situation.

Indeed. Although I wouldn't be using Strings to represent gender, I'd write a Gender class

Person man = new Person("John C. Random", "wibble");

// oops

BTW, an interface is implicitly abstract, there's no need to specify that!

georgemca at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 6
Just an enum would be enough for Gender.
Kamal-Mettanandaa at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 7

> But what's your opinion on the use of inheritance to

> express genders?

As you can see in my design, I don't apply concrete inheritance for anything. Using Interface inheritance is best practice.

Two strong cases I can see for concrete inheritence are for complex behavior and for classes that are using third-party software. To apply concrete inheritence for data fields is not good design, in my opinion, and doesn't go well with my programming style.

For example, I have an application specific Action class which extends the Struts Action class. In this class there is a method for returning an XML document to the browser, rather than returning the ActionForward. All of the application's Action classes inherit from this class and call on the XML publishing method when needed. In this fashion, I add the XML publishing feature to the Controller.

I would simply use an int to represent gender. 1=male, 0=female.

Person p = new PersonImpl("Tom Test", 1);

GhostRadioTwoa at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 8
> I would simply use an int to represent gender.> 1=male, 0=female.> > Person p = new PersonImpl("Tom Test", 1);That's awful. Use an Enum. Gender and numbers have nothing in common.
es5f2000a at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 9

Thx for all your replies already, I'm really learning a lot through these discussions :)

So using an enum for gender would be something like this:

public enum Gender {

MALE, FEMALE

}

and then create a person like:

Person person = new Person("Jane Doe", Gender.FEMALE);

and for the mutator/accessor methods in Person:

private Gender gender;

private String name;

public Person(String name, Gender gender) {

this.name = name;

this.gender = gender;

}

public void setGender(Gender gender) {

this.gender = gender

}

public Gender getGender() {

return this.gender;

}

?

and also, why do you make Person serializable?

Message was edited by:

dfvdfvdfvxfv

dfvdfvdfvxfva at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 10
> That's awful. Use an Enum. Gender and numbers have> nothing in common.Exactly, this is what I also said.
Kamal-Mettanandaa at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 11

I created something concrete now, could you please take a look and say where I can improve the design?

The Person Interface:

public interface Person implements java.io.Serializable {

public String getPersonName();

public Gender getPersonGender();

public void getIdentification();

}

A concrete implementation for the Person Interface:

public class PersonImpl implements Person {

private String name;

private Gender gender;

public PersonImpl(String name, Gender gender) {

this.name = name;

this.gender = gender;

}

public String getPersonName() {

return this.name;

}

public Gender getPersonGender() {

return this.gender;

}

public void getIdentification() {

System.out.println("person: name = " + getPersonName() + ", gender = " + getPersonGender());

}

}

Enum for genders:

public enum Gender {

MALE,FEMALE

}

A class named God for creating and destroying persons.

I made this class because a person cannot create itself, so I think that these methods are not the responsibility of the PersonImpl class and the use of a creational class like the God class is appropriate?

I also tried to apply the singleton pattern for the God class, is it implemented correctly?

public class God {

private static God god;

private God() {

god = new God();

}

public static Person createPerson(String name, Gender gender) {

Person person = new PersonImpl(name, gender);

return person;

}

public static void destroyPerson(Person person) {

person = null;

}

public static God getGod() {

return god;

}

}

The main application:

public class GameOfLife {

private static God god;

public static void main(String[] args) {

god = God.getGod();

Person adam = god.createPerson("Adam", Gender.MALE);

adam.getIdentification();

Person eve = god.createPerson("Eve", Gender.FEMALE);

eve.getIdentification();

}

}

Message was edited by:

dfvdfvdfvxfv

dfvdfvdfvxfva at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 12
Another question I ask myself: is the Person Interface actually necessary now that we use an enum for gender and we only have 1 Person class and no subclasses for Male, Female?
dfvdfvdfvxfva at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 13

Initializing at the start will be good as;

private static God god = god = new God();

And the below has no use.

public static void destroyPerson(Person person) {

person = null;

}

>>Another question I ask myself: is the Person Interface actually necessary >>now that we use an enum for gender and we only have 1 Person class >>and no subclasses for Male, Female?

Having an interface would be always helpful.

Kamal-Mettanandaa at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 14

I don't really understand this:

> private static God god = god = new God();

But I refactored the God class a bit now like this:

public class God {

private static God god;

private God() {

god = new God();

}

public static Person createPerson(String name, Gender gender) {

Person person = new PersonImpl(name, gender);

return person;

}

public static God getInstance() {

return god;

}

}

and in the Main App:

public class GameOfLife {

private final static God god = God.getInstance();

public static void main(String[] args) {

Person adam = god.createPerson("Adam", Gender.MALE);

adam.getIdentification();

Person eve = god.createPerson("Eve", Gender.FEMALE);

eve.getIdentification();

}

}

dfvdfvdfvxfva at 2007-7-12 20:03:17 > top of Java-index,Other Topics,Patterns & OO Design...
# 15

RE: Enum v.s 1=male, 0= female

Does anyone here really believe that a computer understands what

an 'enum' is?

For technical folk, does an 'enum' travel across the wire or does 0s and 1s travel across the wire?

Special message for those that know:

0100010101110110011001010111001001111001011011110110111001100101001000000110100001100101011100100110010100100000011101000110100001101001011011100110101101110011001000000111010001101000011001010111100100100000011000010111001001100101001000000111001101110101011000110110100000100000011100110110110101100001011100100111010001111001001000000111000001100001011011100111010001110011

GhostRadioTwoa at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 16

The concept of a typesafe enum has been around a

long time, and their use in preference of int

constants is good computer science. If you'd like to

discuss computer science, I'm happy to do so. If

you're going to be obnoxious in addition to wrong,

you can do it by yourself.

es5f2000a at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 17

The problem with the code you posted is: when does the

constructor get called? I would change it to look like this:

public class God {

private static final God INSTANCE= new God();

private God() {

}

public static Person createPerson(final String name,

final Gender gender) {

return new PersonImpl(name, gender);

}

public static God getInstance() {

return God.INSTANCE;

}

}

es5f2000a at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 18

> RE: Enum v.s 1=male, 0= female

>

> Does anyone here really believe that a computer

> understands what

> an 'enum' is?

>

> For technical folk, does an 'enum' travel across the

> wire or does 0s and 1s travel across the wire?

You're joking, right?

If you're seriously going to use that as an argument for why you shouldn't use an enum for gender, then you should not be using classes, objects, strings etc.

And no, ones and zeros don't go over the wire. Electric fields do in response to voltage changes. So if you really buy into your argument, then presumably you're directly manipulating the voltages at various points inside your computer.

jverda at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 19

> The concept of a typesafe enum has been around a

> long time, and their use in preference of int

> constants is good computer science. If you'd like

> to

> discuss computer science, I'm happy to do so. If

> you're going to be obnoxious in addition to wrong,

> you can do it by yourself.

It's true that Ghostie is both obnoxious and wrong, but he's not the OP.

jverda at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 20

> RE: Enum v.s 1=male, 0= female

>

> Does anyone here really believe that a computer

> understands what

> an 'enum' is?

>

> For technical folk, does an 'enum' travel across the

> wire or does 0s and 1s travel across the wire?

>

>

> Special message for those that know:

>

> 010001010111011001100101011100100111100101101111011011

> 100110010100100000011010000110010101110010011001010010

> 000001110100011010000110100101101110011010110111001100

> 100000011101000110100001100101011110010010000001100001

> 011100100110010100100000011100110111010101100011011010

> 000010000001110011011011010110000101110010011101000111

> 1001001000000111000001100001011011100111010001110011

Oh, come off it. Of course a computer doesn't understand what an enum is. But nor does it understand any other Java language construct, or any other programming language construct, or indeed anything at all. "Understanding" isn't really a term that can be applied to a machine, it simply responds to voltage changes. But regarding whether it can appear to understand an enum, an enum is no different to any other array of bytes in memory, so why have you suddenly decided enums, above all, are The Great Irrelevan Abstraction? This is a really weak attempt to back-pedal out of a corner, would it really hurt your ego that much to just concede that someone else has a point?

georgemca at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 21
> It's true that Ghostie is both obnoxious and wrong,> but he's not the OP.I know. I meant that I'd ignore him in particular if he couldn't maintain a civil tone, that's all.
es5f2000a at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 22

> If you're seriously going to use that as an argument

> for why you shouldn't use an enum for gender, then

> you should not be using classes, objects, strings

> etc.

I only mention using a 1 for male and 0 for female.

>

> And no, ones and zeros don't go over the wire.

> Electric fields do in response to voltage changes.

Yes, you are correct ... and electric charge = 1 and no charge = 0.

So, eventually everything is converted into bytes and bytes are transformed into electric fields.

GhostRadioTwoa at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 23

> > If you're seriously going to use that as an

> argument

> > for why you shouldn't use an enum for gender, then

> > you should not be using classes, objects, strings

> > etc.

>

> I only mention using a 1 for male and 0 for female.

>

> >

> > And no, ones and zeros don't go over the wire.

> > Electric fields do in response to voltage changes.

>

> Yes, you are correct ... and electric charge = 1 and

> no charge = 0.

Not at all. RS232 for example, represents 0 with a positive current of 15 volts, and 1 with a negative current of 15 volts. There is never not a voltage across a working serial line. I don't know of any comms system which uses the absence of a current to represent a bit (but I bet someone else will come up with an example), turning the voltage on and off would make maintaining a reliable frequency problematic, whereas utilizing an alternating current has the handy side-effect of giving us a frequency with which to synchronize clocks and two states with which to represent the binary system. Electronics are not especially well-suited to computing, they're just the best thing we've got at the moment!

> So, eventually everything is converted into bytes and

> bytes are transformed into electric fields.

Yes, eventually all data does so. Which brings us back again to why you suddenly decided to pick enums as "not existing" because of this current phenomenon present in electronic computers

georgemca at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 24

> The problem with the code you posted is: when does

> the

> constructor get called? I would change it to look

> like this:

>

> > public class God {

>private static final God INSTANCE= new God();

>private God() {

>}

>

> public static Person createPerson(final String

> name,

>final Gender gender) {

> urn new PersonImpl(name, gender);

>}

>public static God getInstance() {

>return God.INSTANCE;

>

> }

>

What purpose does that instance of God serve, though? No need for it

georgemca at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 25
> What purpose does that instance of God serve, though?> No need for itNo purpose. :)Either the createPerson() method should be static, or you can use a singleton, but both is just me being silly.
es5f2000a at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 26

> > If you're seriously going to use that as an

> argument

> > for why you shouldn't use an enum for gender, then

> > you should not be using classes, objects, strings

> > etc.

>

> I only mention using a 1 for male and 0 for female.

So?

What's special about that case vs. usng enum

in any other situation? Either that's special

(which it's not) or enum is universally useless

(which it's not), or your initial "argument" is

bullshit (which it is).

>

> >

> > And no, ones and zeros don't go over the wire.

> > Electric fields do in response to voltage changes.

>

> Yes, you are correct ... and electric charge = 1 and

> no charge = 0.

Wrong.

A particular voltage in a particular context is

interpreted as 1, and a particular different voltage

in that same context is interpreted as 0. Just as a particular bit pattern is interpreted as

Sex.male vs. Sex.female.

> So, eventually everything is converted into bytes and

> bytes are transformed into electric fields.

Yes. Thanks for making my point and admitting

you were full of krap.

jverda at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 27

> What's special about that case vs. usng enum

> in any other situation? Either that's special

> (which it's not) or enum is universally useless

> (which it's not), or your initial "argument" is

> bullshit (which it is).

>

Yes it is indeed :o)

> A particular voltage in a particular context is

> interpreted as 1, and a particular different

> voltage in that same context is interpreted as 0. Just

> as a particular bit pattern is interpreted as

> Sex.male vs. Sex.female.

Thanks for explanation.

> So, eventually everything is converted into bytes

> and bytes are transformed into electric fields.

> Yes. Thanks for making my point and admitting

> you were full of krap.

Just trying to help a bit.

GhostRadioTwoa at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 28

> > What's special about that case vs. usng enum

> > in any other situation? Either that's special

> > (which it's not) or enum is universally useless

> > (which it's not), or your initial "argument" is

> > bullshit (which it is).

> >

>

> Yes it is indeed :o)

>

> A particular voltage in a particular context is

> interpreted as 1, and a particular different

> voltage in that same context is interpreted

> as 0. Just

> as a particular bit pattern is interpreted as

> Sex.male vs. Sex.female.

>

> Thanks for explanation.

>

> > So, eventually everything is converted into bytes

> > and bytes are transformed into electric fields.

> > Yes. Thanks for making my point and admitting

> > you were full of krap.

>

> Just trying to help a bit.

I don't want to get into a flamewar, but posting inaccurate information and claiming it to be "irrefutable" or "undebatable", quoting ancient SSADM books or passages from SCJP books and describing it as "a best practice", absolutely refusing to ever admit a mistake, and trying to discredit anyone with whom you disagree by claiming they simply aren't capable of understanding what you're saying isn't particularly helpful

georgemca at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 29
Thanks for sharing :o)
GhostRadioTwoa at 2007-7-21 22:35:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 30
> Thanks for sharing :o)You're more than welcome
georgemca at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 31

> > What's special about that case vs. usng enum

> > in any other situation? Either that's special

> > (which it's not) or enum is universally useless

> > (which it's not), or your initial "argument" is

> > bullshit (which it is).

> >

>

> Yes it is indeed :o)

Then what was the point? Was it a joke? Because it looked to me at least like you thought 1 and 0 are preferable to an enum for representing male/female.

jverda at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 32

> > > What's special about that case vs. usng enum

> > > in any other situation? Either that's special

> > > (which it's not) or enum is universally useless

> > > (which it's not), or your initial "argument" is

> > > bullshit (which it is).

> > >

> >

> > Yes it is indeed :o)

>

> Then what was the point? Was it a joke? Because it

> looked to me at least like you thought 1 and 0 are

> preferable to an enum for representing male/female.

Means he hadn't thought of enums, but didn't want to admit it. Give him some period pains, and you've got instant UJ :-)

georgemca at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 33

> Then what was the point? Was it a joke? Because it

> looked to me at least like you thought 1 and 0 are

> preferable to an enum for representing male/female.

No, that was not a joke. I would prefer to use 1 and 0. Enum might be interpreted as a better option by some. It is a small detail for me. I rather focus more on bigger issues such as maintaining low coupling and pooling database connections.

Either an enum, 1 or 0, or a special Gender class, as mentioned, would work.

My hand coding experience with Java was mostly pre-version 1.5, before an enum type existed. As a result, I personally might not be quick to jump on new fangled additions :o) Most of my Java work is done in UML nowadays.

GhostRadioTwoa at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 34

> > Then what was the point? Was it a joke? Because it

> > looked to me at least like you thought 1 and 0 are

> > preferable to an enum for representing

> male/female.

>

> No, that was not a joke. I would prefer to use 1 and

> 0.

Why? What advantage is there?

> Enum might be interpreted as a better option by

> some.

Only by those who know what they're talking about.

> It is a small detail for me. I rather focus

> more on bigger issues such as maintaining low

> coupling and pooling database connections.

Code that's easy to understand, compile-time value-safe, and clearly expresses the programmer's intent is not a "bigger issue" for you?

> My hand coding experience with Java was mostly

> pre-version 1.5, before an enum type existed.

> As a result, I personally might not be quick to jump

> on new fangled additions

It's not that new-fangled. The concept has been around for a long time, 1.5 has been out for quite a

while, and hand-rolled typesafe enums were a very common pattern before 1.5. (I was using them as far

back as 1.3, and I saw quite a few references to them not long after I started using them.)

jverda at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 35

> It's not that new-fangled. The concept has been

> around for a long time, 1.5 has been out for quite a

> while, and hand-rolled typesafe enums were a very

> common pattern before 1.5. (I was using them as far

> back as 1.3, and I saw quite a few references to them

> not long after I started using them.)

Josh Bloch's excellent Effective Java described hand-rolled typesafe

enums. It came out in 2001.

es5f2000a at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 36

> > It's not that new-fangled. The concept has been

> > around for a long time, 1.5 has been out for quite

> a

> > while, and hand-rolled typesafe enums were a very

> > common pattern before 1.5. (I was using them as

> far

> > back as 1.3, and I saw quite a few references to

> them

> > not long after I started using them.)

>

> Josh Bloch's excellent Effective Java described

> hand-rolled typesafe

> enums. It came out in 2001.

Sounds about right. I created my own in 2000 or 2001 and heard about somebody else's--probably Bloch's--shortly after that.

jverda at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 37

> > > Then what was the point? Was it a joke? Because

> it

> > > looked to me at least like you thought 1 and 0

> are

> > > preferable to an enum for representing

> > male/female.

> >

> > No, that was not a joke. I would prefer to use 1

> and

> > 0.

>

> Why? What advantage is there?

Your enum contains references to objects on the stack. Objects are larger data structures than primitives. They use more memory space.

If I simply use an int rather than three objects ((1)enum, (2) String (male), (3) String (female)) I utilize less memory.

This is part of the Every Byte Counts Strategy for Efficient Information Systems Development. et. al.

GhostRadioTwoa at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 38

> > > No, that was not a joke. I would prefer to use 1

> > and

> > > 0.

> >

> > Why? What advantage is there?

>

> Your enum contains references to objects on the

> stack. Objects are larger data structures than

> primitives. They use more memory space.

In the heap, actually, at least in current VMs.

In any case, there's only one instance of each enum value object created. I'd have to define a

hell of a lot of them--millions of distinct enum values--for that to be an issue in any environment other than a very tiny J2ME.

What I will have is a bunch of references to these objects, which are 4 bytes, same as an int.

You're talking about a microoptimization that will probably have no noticeable effect in the staggeringly

vast majority of cases.

jverda at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 39

public enum Suit { clubs, diamonds, hearts, spades }

For this example enum, there would be one enum object and four String objects in the heap?

I forgot the stuff about the String literal pool. Would there be four instances of String or only one and a pool of values?

GhostRadioTwoa at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 40

> public enum Suit { clubs, diamonds, hearts,

> spades }

>

> For this example enum, there would be one enum object

> and four String objects in the heap?

There will be four Suit enum objects. There will probably be four String objects and maybe some additional support objects. Not sure of the details.

That doesn't really matter though, because if I have an Suit[] with a million entries and an int[] with a milion entries, both arrays will take up the same amount of space--one million times four bytes (plus small overhead).

There will only ever be four Suit objects for the whole classloader, regardless of how many Suit variables I declare and set.

> I forgot the stuff about the String literal pool.

The literal pool isn't really what I was talking about, though I'd guess that's used for the string values. I was talking about the enum objects themselves.

jverda at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 41

Thanks.

> That doesn't really matter though, because if I have

> an Suit[] with a million entries and an int[] with a

> milion entries, both arrays will take up the same

> amount of space--one million times four bytes (plus

> small overhead).

public class JumboShrimp {

private Object taste;

private Object size;

...

}

If you have (group #1 = an array of 1,000 int values), and you have (group #2 = an array on 1,000 JumboShrimp objects).

Which group of data (the array including the primitives and objects) would take up more memory/space on the heap?

Basically, which one takes up more memory, 1,000 ints or 1,000 JumboShrimp objects?

GhostRadioTwoa at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 42

> > > > Then what was the point? Was it a joke?

> Because

> > it

> > > > looked to me at least like you thought 1 and 0

> > are

> > > > preferable to an enum for representing

> > > male/female.

> > >

> > > No, that was not a joke. I would prefer to use 1

> > and

> > > 0.

> >

> > Why? What advantage is there?

>

> Your enum contains references to objects on the

> stack. Objects are larger data structures than

> primitives. They use more memory space.

Did your extensive performance testing highlight this as a problem? As Jeff said, this is unlikely to have any impact on performance whatsoever. Objects aren't especially expensive any more

georgemca at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 43

> Did your extensive performance testing highlight this

> as a problem? As Jeff said, this is unlikely to have

> any impact on performance whatsoever. Objects aren't

> especially expensive any more

I never mentioned any sort of problem. I expressed a programming preference and also mentioned that creating a Gender class, as you mentioned, also would work.

In regards to 1,000 JumboShrimp objects and 1,000 ints, I am certain that the JumboShrimp objects take up more memory.

GhostRadioTwoa at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 44

> > Did your extensive performance testing highlight

> this

> > as a problem? As Jeff said, this is unlikely to

> have

> > any impact on performance whatsoever. Objects

> aren't

> > especially expensive any more

>

> I never mentioned any sort of problem. I expressed a

> programming preference and also mentioned that

> creating a Gender class, as you mentioned, also would

> work.

Just that your method of justifying that preference was somewhat unusual!

> In regards to 1,000 JumboShrimp objects and 1,000

> ints, I am certain that the JumboShrimp objects take

> up more memory.

I absolutely agree with you. This is indeed an indisputable fact! However, whether or not this actually matters is unknown. If memory usage and speed of invocation were of such an importance, one would probably be advised not to use Java at all

georgemca at 2007-7-21 22:35:56 > top of Java-index,Other Topics,Patterns & OO Design...
# 45

> Just that your method of justifying that preference

> was somewhat unusual!

:o)

> > In regards to 1,000 JumboShrimp objects and 1,000

> > ints, I am certain that the JumboShrimp objects

> >take up more memory.

>

> I absolutely agree with you. This is indeed an

> indisputable fact! However, whether or not this

> actually matters is unknown. If memory usage and

> speed of invocation were of such an importance, one

> would probably be advised not to use Java at all

Great point!

GhostRadioTwoa at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 46

> I absolutely agree with you. This is indeed an

> indisputable fact! However, whether or not this

> actually matters is unknown. If memory usage and

> speed of invocation were of such an importance, one

> would probably be advised not to use Java at all

Er, bait and switch?

Obviously, if you add data members to the enum and don't try to represent them in the primitive solution, the enum will be heavier. How is the int solution representing the attributes that were added to the enum?

You find yourself right back where you started.

es5f2000a at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 47

> Thanks.

>

> > That doesn't really matter though, because if I

> have

> > an Suit[] with a million entries and an int[] with

> a

> > milion entries, both arrays will take up the same

> > amount of space--one million times four bytes

> (plus

> > small overhead).

>

> [code]public class JumboShrimp {

>private Object taste;

> private Object size;

>...

> ode]

>

> If you have (group #1 = an array of 1,000 int

> values), and you have (group #2 = an array on 1,000

> JumboShrimp objects).

>

> Which group of data (the array including the

> primitives and objects) would take up more

> memory/space on the heap?

>

> Basically, which one takes up more memory, 1,000 ints

> or 1,000 JumboShrimp objects?

That's not relevant. We won't have 1000 instances of the enum.

For a "normal" class, sure, you can create 1000 objects, and they'll take up more

space than the int. But you can't have 1000 enums

(unless you define 1000 values for that enum).

If we have an enum with 4 values, there will only ever be 4 enum objects of that class. So in the above, if

JumboShrimp is an enum with 4 values, then there will be 4 JumboShrimp objects, not 1000.

Both arrays will take up the same space regardles. Arrays hold primitives or references, not objects. The

objects pointed to by the JS array will take up more space if there are 1000 of them, but if JS is a 4-element

enum, there won' be 1000 of them.

jverda at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 48

From this code, we can see that an array of 5 million ints, an array of 5 million references to enums, and an array of 5 million references

to "normal" objects each take up about 19 MB, which is what we'd expect, given that ints and references consum 4 bytes each.

We can also see that populating the enum array doesn't increase the memory usage. We're not creating new instances of the enum because we CAN'T.

Populating the "normal" object array with newly created instances does consume memory, as expected.

In short, your argument for using ints instead of enums to use less memory doesn't hold water.

:; java -cp classes -Xms128m -Xmx128m EnumSize

free/total mem (MB) = 126/127

created int array

free/total mem (MB) = 107/127

created Foo array

free/total mem (MB) = 88/127

0 Foos

free/total mem (MB) = 88/127

1000000 Foos

free/total mem (MB) = 88/127

2000000 Foos

free/total mem (MB) = 88/127

3000000 Foos

free/total mem (MB) = 88/127

4000000 Foos

free/total mem (MB) = 88/127

populated Foo array

free/total mem (MB) = 88/127

created Bar array

free/total mem (MB) = 69/127

0 Bars

free/total mem (MB) = 68/127

10 Bars

free/total mem (MB) = 59/127

20 Bars

free/total mem (MB) = 49/127

30 Bars

free/total mem (MB) = 40/127

40 Bars

free/total mem (MB) = 30/127

50 Bars

free/total mem (MB) = 21/127

60 Bars

free/total mem (MB) = 11/127

70 Bars

free/total mem (MB) = 2/127

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

import java.util.*;

public class EnumSize {

public static void main(String[] args) throws Exception {

checkMem();

int[] intArr = new int[5000000];

System.out.println("created int array");

checkMem();

System.out.println();

Foo[] fooArr = new Foo[5000000];

Foo[] fooValues = Foo.values();

System.out.println("created Foo array");

checkMem();

System.out.println();

for (int ix = 0; ix < fooArr.length; ix++) {

fooArr[ix] = fooValues[ix % 4];

if (ix % 1000000 == 0) {

System.out.println(ix + " Foos");

checkMem();

}

}

System.out.println();

System.out.println("populated Foo array");

checkMem();

System.out.println();

Bar[] barArr = new Bar[5000000];

System.out.println("created Bar array");

checkMem();

System.out.println();

for (int ix = 0; ix < barArr.length; ix++) {

barArr[ix] = new Bar();

if (ix % 10 == 0) {

System.out.println(ix + " Bars");

checkMem();

}

}

System.out.println();

System.out.println("populated Barr array");

checkMem();

}

static void checkMem() {

Runtime rt = Runtime.getRuntime();

System.out.println("free/total mem (MB) = " + rt.freeMemory() / 1024 / 1024 + "/" + rt.totalMemory() / 1024 / 1024);

}

static enum Foo { foo1, foo2, foo3, foo4 }

static class Bar {

int[] arr = new int[250000]; // one Bar instance will use up about a million bytes

}

}

jverda at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 49

> In short, your argument for using ints instead of

> enums to use less memory doesn't hold water.

In reality, I never argued for using ints instead of enums to use less memory.

First, you ignored my question, which was if 1,000 ints take up more or less memory than 1,000 JumboShrimp objects.

Second, you continued to prove an irrelevant point. Yes, it is common understanding that an array contains only references. So, an array of 1,000 ints and an array of 1,000 references to enum objects would take up the same amount of memory.

I don't see any discussion about populating arrays. But, it is nice to see someone very enthusiastic about their point.

Using primitives or objects to represent things is in some degree a personal programming preference. If you wanted to create a Gender class, that is fine. If you wanted to use 1 and 0 to represent male and female that is fine too.

GhostRadioTwoa at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 50

> > In short, your argument for using ints instead of

> > enums to use less memory doesn't hold water.

>

> In reality, I never argued for using ints

> instead of enums to use less memory.

I believe you stated that that's your reason for doing so.

In any case, you have not provided any good reason to use ints over enums.

> First, you ignored my question, which was if 1,000

> ints take up more or less memory than 1,000

> JumboShrimp objects.

I did not ignore it. I explained why it's irrelevant as asked. I then wrote code that shows that.

> Second, you continued to prove an irrelevant point.

Not in the least.

> Yes, it is common understanding that an array

> contains only references. So, an array of 1,000 ints

> and an array of 1,000 references to enum objects

> would take up the same amount of memory.

I know that. I'm trying to clear up *your* sloppy wording.

> I don't see any discussion about populating arrays.

Huh?

The size difference between an int and an enum only matters of there are a LOT of them. The easiest way to get a lot of something is to stick a bunch of 'em into an array. As I have explained and demonstrated, even when you have "a LOT" of enums, you really don't, because enums are multitons of a sort.

> If you

> wanted to use 1 and 0 to represent male

> and female that is fine too.

Not on my team.

There are several reasons to prefer enums and zero reasons to prefer ints. Sticking to ints when a better solution exists just because you "like them more" will not fly in a professional shop.

jverda at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...
# 51

> Using primitives or objects to represent things is in

> some degree a personal programming preference. If you

> wanted to create a Gender class, that is fine. If you

> wanted to use 1 and 0 to represent male

> and female that is fine too.

Personal preference to a very small degree. If it is conceivable that, for instance, a gender value of 9 could be assigned, you would have to code defensively for that, which is a shame because Java offers us static typing that would allow us to not bother. No point arguing that it wouldn't happen, how many times do we see questions asking about what the numeric value of Calendar.DAY is, and does it change? Maintenance coders could easily think along these lines and break your code. You have a duty as a professional to consider this

If all you're interested in is male and female - as opposed to allowing "unspecified, "unknown", "third gender" and the like - wouldn't boolean be a more appropriate primitive to use anyway?

georgemca at 2007-7-21 22:36:01 > top of Java-index,Other Topics,Patterns & OO Design...