Studying Objects and Classes - java

I have a test later today, and I think I may be stuck on this part of the study guide:
Classes and objects, references, methods; the class as a pattern for
creating objects, the concept of a class and object as defining a unit
with data members and methods; what is an instance of a class; static
members of a class; what it means for a member of class to be public
My best effort to explain these concepts is, as follows:
A class is a programmer defined data type that is composed of data
members and methods.
An object is an entity consisting of values
(characteristics and traits) and methods (capabilities or behaviors).
A class is like a blueprint from which objects are created.
A reference variable points to an object created in another memory location. (not 100% sure what this means)
Much like a cookie cutter can be used to create individual cookies, a class can
be used to create individual objects, or instances of that class.
A static member of a class (or class variable or method) belongs
to the class and is not owned by any object of the class.
If a member of a class is public, that means that it can be accessed by other parts of the program.
I'm wondering if this is going to be satisfactory or if I'm missing anything critical. Obviously I'm shaky on the idea of reference and reference variables, and I think I'm still trying to conceptualize objects and classes in a way that's sufficiently explainable.
Thanks for your help, in advance.

A class is a template from which objects can be built; it acts as a blueprint for creating objects.
An object is an instance of a class.
Much like how an architect draws a blueprint of a house. The blueprint and constructed house are two different things. From that one blueprint, the same house can be built in a lot of places. Similarly, you can create multiple objects of a class.
The blueprint defines how a house is supposed to look like. There is going to be a kitchen, a couple of bedrooms, a basement (possibly for hiding illegal money), etc. Each person who buys a house will customize the house in a different way.
This is akin to values in an object - same variables in different objects may have different values.
Get it? Same bedroom in two different houses constructed from the same blueprint will have different color, bed, lighting, etc. Same thing, different value.
Here is how you understand static and instance variables. The kitchen belongs to everyone - it is static and is shared by everyone and only one kitchen exists (static). Your guitar belongs to you and you only, it is not shared with anyone but it may happen that you sister also has a guitar that belongs to her and her only.
What I am saying is - every object has its own copy of instance variables while there is only one copy of static variables that is shared by all the objects of that class.
Here is how to understand changing the values of static and instance variables
If you were to get custom graphics for your guitars, it will matter to you and you only because it is an instance variable. If there was some change made to the kitchen, say the fridge was moved, it affects everyone because kitchen is a static variable.
What I am saying is - changes to instance variables are only visible to the object that owns them while changes to static variables are visible to all the objects of that class.

Seems pretty spot-on to me. If I'm being pedantic, I'd recommend changing the last two sentences:
A static member of a class belongs to the class and is not owned by
any instance of the class.
If a member of a class is public, that means that it can be accessed
by other classes within the program.
To understand references, you also might want to read this: http://www.javaranch.com/campfire/StoryCups.jsp
And its follow-up: http://www.javaranch.com/campfire/StoryPassBy.jsp

You seem to have everything else nailed down pretty pat. For newbies, reference types and reference variables are continuous points of contention because they have a tendency to get confused with something else.
The easiest way to understand reference types is to compare it in terms of houses. Your house is the value, your street address is a pointer to your house (a reference), and your full address -- could -- be considered to be your reference variable when used on an envelope.
See what I did there?

For the most part, you seem to have the material down. I'm going to try and answer your implied question here,
A reference variable points to an object created in another memory location. (not 100% sure what this means)
A reference (in Java) is a bit like a po box number. You can go to the post office and find lots of po boxes, but the number makes the specific box easy to find. Also, it is unique within the post office. It ensures the mail is kept separate from the other boxes. The analogy is not perfect (note the key is largely immaterial to this discussion).

Yes you are spot on with classes and how objects are instances of them. A class is like a template that contains all the attributes/characteristics. Within a class, there can be objects, which are more of instances of the class. For an example, say there's a class called 'Animal'. That means whatever items are in the class all have one thing in common: they're animals. Now, an object of the class 'Animal' would be a specific animal (bird, elephant, giraffe, dog). These would be objects under the class 'Animal' because they're all animals, but they're objects because they are instances of animals (kinds of animals). Also, when a member/method of a class is public, it can be accessed by other parts of the program or project. Hope this helps.

Related

Are instances of Class immutable?

I was wondering whether Class instances are immutable. The declared methods names do not suggest that the instance state is changed when they are invoked, but I found no explicit guarantee on the javadoc.
Scenario: I need to store unique class names in a Set. Ideally, I would like to populate the set with Class instances to avoid unnecessary calls to Class.forName() when I need to access the classe via reflection. However, it preferable to use immutable objects as keys of sets. Hence I was wondering if I could use Class instances right away.
First, The generics part Class<?> really doesn't matter here. Sure, no raw types, so Class<?> is better than Class, but for your question, the wildcard doesn't matter.
So in essence, you are asking whether Class objects are immutable. And for all practical purposes, they are.
Class objects come into existence when a class loader loads a class, and they stay put unless the whole class loader is unloaded, and everything it loaded with it.
Which can't happen when such class objects are still used in a map somewhere.
On the other hand: Class.forName() shouldn't be too expensive for classes already loaded. And when things such as serialization come into play, people suggest to go with String instead of Class objects for example (see here).
One has to distinguish between the immutable identity of a class object, and the actual "code" belonging to the class. That code can be changed at runtime (by instrumentation, think hot swap of code). But the class name, and its each code, and equals() equality should not be affected by that. Because the "identity" stays the same.
Final note: as the interesting comments below lay out, there are certain ways to alter Class objects to a certain degree. But all of these activities are definitely "out of the norm". Therefore: theoretically, you might prefer Strings over Class objects, but practically, in "normal" applications, using Class should work fine, too.
As I don’t really agree with other answer I decided to write this one,
Classes are not immutable, but they are unique - only one instance of Class object can exist for one class.
BUT class it not defined by its name, as classes might be from different class loaders, and different class loaders might have classes with same names - but that will be different classes, you would get ClassCastException if you would pass some object between code handled by 2 different class loaders if that object type would exist in both of them (as separate one, not inherited).
Class instances can be still safely used in Set, as they use default implementation of hashset/equals so only same instances of Class will be considered equals.
But to decide if you should use String or Class you need to know how exactly your app is supposed to work, as like I said, multiple classes with same name can exist between different class loaders.
And by just storing class name you can’t be sure that Class.forName will return same instance as expected it might even load some other class with same name from current class loader instead of using expected one.

Can a class instance variable be excluded from a subclass in Java?

Possibly a dumb question, but pretend class Node has an instance variable called strength. And pretend class Episode, which extends Node, does not need strength (other subclasses do). Pretend also that there are a LOT of Episode nodes all storing an instance of strength. Is there any way in Java to say "this subclass does not have a strength variable"? I'm kind of seeing why this probably isn't allowed, but thought I'd check.
Update: Thanks all. As I suspected, the answer to this question is "no," but creating a subclass of Node with the variables/methods not needed by Episode, then connecting the other (sub)subclasses that need these variables/methods to that new subclass will do exactly what I want.
No, it's not possible. You can have e.g. Node and StrengthNode classes, one without strength and one with it, then Episode class will extend Node, others will extend StrengthNode.
Also, take into account the access control in Java, as if strength is a private variable in Node, it will not be accessible in Episode class directly (only using getter method), but it's instance will exist in memory anyway.
Well The only way i can think around this is if your problem with the size of the object your instance variable stores either you can initialize the parameter to null or you can serialize the object with specifiying your instance parameters to be transient and go with serialize it , deserialize it .
This was just a thought around that , cant think of anything closer.
if you specifically dont need exact inheritance you go around that with creating a custom factory and extract the member variable using reflection , that would work too.
Anyway thats my opinion.

How does serialization reconcile static members?

Being a newbie, I'm trying to understand serialization and I don't get why one would need to reassign static fields after deserialization (as some suggest in order to keep original values) if by definition all objects of the same class have the same values of static parameters. Isn't it true that a new object automatically receives all static parameters of its class? I mean if deserialization nullifies object's static members and we keep the original object wouldn't that mean that there will be two objects of the same class with different values of static parameters? How's that possible or how am I wrong?
EDIT:
It seems that I wasn't clear enough and I'm sorry about that.
When writing my first sentence I was keeping in mind Bruce Eckel's "Thinking in Java" (4th Ed.). I'm not sure if I can attach a few scans of his book without violating copyright but I actually stumbled upon the last example in "Object serialization" chapter (pp.715-718). By means of his io/StoreCADState.java and io/RecoverCADState.java Eckel gets objects of the same class with different static values. He doesn't go deep enough for me into explanation and I feel totally confused.
I know that static members belong to a class not an object. Although I'm not sure now what it means precisely. I used to believe it implied that whenever an object is created a set of static parameters is 'taken' from the class description and 'added' to an object. If this is correct then why they are not 'added' to an object after deserialization when Object instance being cast to a specific class?
Have a look at the Javadoc for static members here. This is what it says:
They are associated with the class, rather than with any object.
As static members are never associated with any object, they are never stored while serializing the object. Also, new object won't automatically receive all static parameters as they have nothing to do with serialization-deserialization of the objects. If you are trying to store static variables with objects then I'd say it's a design flaw. We should rather declare them as non static if we want to persist their values with objects.
Update:
If you want to store non serializable fields with object then you can do so by writing your implementation of readObject() and writeObject() methods. Have a look at the answer of this SO question for example.
How does serialization reconcile static members?
It doesn't.
I don't get why one would need to reassign static fields after deserialization
You don't.
(as some suggest in order to keep original values)
They're wrong.
if by definition all objects of the same class have the same values of static parameters.
Objects don't have values of static parameters at all. The static members are in the class, not in the object.
Isn't it true that a new object automatically receives all static parameters of its class?
No.
I mean if deserialization nullifies object's static members
It doesn't.
and we keep the original object wouldn't that mean that there will be two objects of the same class with different values of static parameters?
No, because it doesn't happen.
How's that possible
It isn't.
or how am I wrong?
Several ways. Serialization does precisely nothing with static members.
EDIT
It seems that I wasn't clear enough and I'm sorry about that.
You were clear enough. You're just fundamentally mistaken about several things.
When writing my first sentence I was keeping in mind Bruce Eckel's "Thinking in Java" (4th Ed.). I'm not sure if I can attach a few scans of his book without violating copyright
You can't (shouldn't) post images of text here, but you can quote a bit of the book under 'fair use' provisions.
but I actually stumbled upon the last example in "Object serialization" chapter (pp.715-718). By means of his io/StoreCADState.java and io/RecoverCADState.java Eckel gets objects of the same class with different static values.
Impossible. You must have misunderstood. Or else he is using different class loaders, which is a complication not mentioned in your question.
He doesn't go deep enough for me into explanation and I feel totally confused. I know that static members belong to a class not an object. Although I'm not sure now what it means precisely. I used to believe it implied that whenever an object is created a set of static parameters is 'taken' from the class description and 'added' to an object.
No. The static data stays where it is, in the class. If there were multiple copies of it, it couldn't possibly work, or be describable as 'static'.
If this is correct
It isn't.
then why they are not 'added' to an object after deserialization
Because Serialization doesn't deal with static objects in any way.
when Object instance being cast to a specific class?
And that process takes place after Serialization, not during it, and doesn't have anything to do with static data either.
Because static members belong to the class, not to the object, they're not serialized or deserialized by default.
A Class with the same name and different values in static members can be only in another namespace (loaded by another ClassLoader).
Read this to understand: How to serialize static data members of a Java class?

State of Object, which don't has any attribute

We all know state of an Object is value of it's attributes (instance variables), but if class doesn't has any attribute (no inherited attributes), what would be the state of an Object of such class.
There is a word for such objects - stateless.
There is no such thing as a Java class without a parent class. The default parent would be used, e.g. java.lang.Object.
At a minimum every instance of a class has two attributes: a reference address and a Class type. Note, not every class can be instantiated. There is also some space used in the ClassLoader and any String(s) may (or may not) be interned. This actual implementation might vary slightly on the specific version of the JDK and run-time platform, and additional optimizations can be added by the JIT. However, as a Java developer you are not responsible for this memory management and I would be wary of premature optimization.
first thing
any class we write in java will extend Object class by default if there is no extends written by the developer.
so each and every class will definitely have a parent with no doubt atleast Object class.
second
if you dont put any attributes in your class , obviously it will get all the instance variables except private gets inherited to your class.
so it will have atleast object state but it will not serve any purpose
An object with no data members and links to other objects is a stateless object and in this form can hardly be of any use.
This kind of classes can nevertheless be usefull, because of its methods. It can be...
a base for a further inheritance. It declares/defines some methods, that could be inherited by derived classes. This class will probably be an abstract class, having no objects at all (although not a condition)
a service class. It can define some methods, which in nature do not belong to concrete objects but are used by other objects. Like some all-purpose mathematical operations, a service that returns a current time or similar. These methods can be static, so again no instances are needed.
We call those object stateless. As the name suggests, they have no state.
Referring to other answers/comments, even though every Java object implicitly extends Object, mind that Object has no fields. So even though every object has a runtime address and class attributes, for all practical purposes you can still consider some objects stateless.
Next, it is definitely not true that stateless objects serve no purpose! You can use stateless object for:
1) Grouping functions with similar functionality, similar to java.lang.Math, which groups mathematical functions.
2) Passing functionality as a parameter, e.g. Comparator<T> can be used to sort objects that do not implement Comparable<T>, and it definitely needs no state.
Stateless objects are somehow similar to immutable objects: their state can never be changed and therefore they are always thread-safe.
You may also want to see JEE Stateless Session Beans which differentiate between a converstional state and an instance state.

Instance Field Declaration in Java

I'm just getting the hang of OOP and have been playing around with Java a lot. One of the troubles I have is deciding whether I need a private instance field for a particular class. Is there a rule of thumb I should be using in terms of whether I need to make something a private instance field of not?
Thanks.
Well, ask yourself whether it's logically part of the state of an instance of the object. Is it something about the object which is valid for the whole lifetime of the object, or is it something which only applies during the course of a single method (in which case it should be a local variable)? Or is it actually applicable to the class itself (in which case it should be static)?
If you could give some examples where you aren't quite sure, that would help.
(Note that I've assumed that the choice here is the kind of variable - static, instance or local. Instance variables should pretty much always be private :)
If it´s a natural part of the object or something the object needs to perform some task on a regular basis then by all means make it an attribute. If it is a constant then you should make it a public class variable (or rather a constant :P). That is, declare it "public static final w/e"
Public instance variables are not used as often because it often leads to messier code. Think as previously stated of the instance variables (or attributes) as the objects state. It´s usualy clearer to change the objects state by performing operations on it rather than juggle publics around. Good luck.
"Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code." Controlling Access to Members of a Class
When learning object-oriented programming, think of it as a way to model real-world concepts as code. Nouns become objects; and the actions done to, on or by the nouns become methods. Instance variables are the properties of those nouns. For instance if you have a class representing a Car, slamOnTheBreaks() would be a method the Driver would call to slam on the breaks, and a Car has some number of seats inside, right? So an instance variable would be int numberOfSeats;.
Think of instance variables on a need-to-know, need-to-change basis. By making numberOfSeats public, that would allow the Driver to change the number of seats in the car, which doesn't make any sense. They only need to know how many seats the car has, which they can find out when they get in the car, or rather, calling the method public int getNumberOfSeats().
As Danny mentioned, the story is different for constants. If a value is a constant, it will remain constant for the entire duration of the program's execution, so for example if you want Driver Bob to be the only Driver for all those Car and Truck objects you create, Bob had better be a.) accessible, a.k.a. public, so he can be in every Car and Truck (assuming no inheritance between Car and Truck), and b.) unable to change.

Categories

Resources