1

Okay, so far I know a lot about java. Databases, URL, SQL, etc. But so far my books and I have only dealt with single class programs. I was wondering something about OOP.

If I have a class that defines an example object and each example object has it's own array.

Ex.

public class Example {
Array exampleArray;
}

does that mean that every 'example' object has it's own unique 'exampleArray' Array object that can be referenced by "insert objectname here".exampleArray ?

Ex.

Example dataBase = new Example();
int length = dataBase.exampleArray.length();

will this work?

sorry, for some reason the line feed isn't working with my example code

4 Answers4

1

Yes, each Example object will have its own unique exampleArray array object. Typically you would make it a private member variable and access it through methods, though, instead of allowing clients to access the array directly.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • whew, this makes things so much easier. Java books really only focus on one class programs, not large scale data management :/ – The Militant Hobo Dec 19 '12 at 20:39
  • @user1827733 If you're using an introductory book on Java, most of the examples probably are going to use a single class to illustrate a point. A good book on data structures with Java examples will give you a taste of OOP and larger-scale data management. For example: http://algs4.cs.princeton.edu/home/ – Bill the Lizard Dec 19 '12 at 20:46
0

Each object that is generated will have it's own set of attributes. So the following code produces two unique objects:

Example first = new Example();  
Example second = new Example();

with unique attributes for each of these objects.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
0

In this particular example, you will get a NullPointerException because you never assigned a value to exampleArray in your class. But in general, yes, each instance of Example has its own unique array.

Thorn G
  • 12,620
  • 2
  • 44
  • 56
  • Thank you, I know I would get a Null Pointer, but I put the bare minimum code to get my point across. – The Militant Hobo Dec 19 '12 at 20:39
  • If you say something doesn't work without providing details and claim to know 'a lot' about a language without understanding object's properties, it's understandable we start at the high level, no? – Philip Whitehouse Dec 19 '12 at 20:45
0

This is a bit off topic but I feel worth mentioning. If you intend to make a copy of a Object, you need to be careful that you make a deep copy. Doing so will cause each to act as though they were instantiated normally. If you don't, they will "share" the attribute.

Community
  • 1
  • 1
Daniel
  • 2,435
  • 5
  • 26
  • 40