Related
Let's say I have a class named Class and I created a new null object:
Class object = null
The constructor in Class is:
private int a;
private String b;
public Class() {
a = 144;
b = "Test";
c = null;
}
Will a, b, and c be equal to null?
If not, is there a way for me to create the object so that all three instance variables are null?
No. They won't be equal to anything because they won't exist. Nothing ever created an instance of Class so there is no instance.
As an analogy you're basically asking, "If I don't build a house, will that house's windows be open or closed?" They will be neither.
When you do this:
Class object = null;
What you have is a variable which can (at a later time) refer to any instance of type Class, but which currently refers to no instance.
is there a way for me to create the object so that all three instance variables are null
Kind of. You can add a constructor which doesn't set those values:
public Class () { }
And you can create an instance of that class via that constructor:
Class object = new Class();
Then you can observe your instance in the debugger to see what those values are. I'm not 100% sure in Java, but it's possible that an int can't be null. Which would make that part of the question kind of moot. (I know it can't in C#, but if it can in Java then ignore this part and carry on.)
An unassigned int local variable would be a compiler error if you try to use it. But this is a class field, not a local variable. In this case it's going to be automatically given its default value, which is generally null for reference types but 0 for primitive numeric types.
Let's say I have a class named Class
Given that java.lang.Class already exists, let's not. Let's say you have a class named MyClass.
and I created a new null object:
That's an oxymoron.
null is a reference. It's not an object. It is, in fact, the reference that means 'I refer to no object', and is the only reference that means 'I point at nothing'.
When you write:
MyClass x = new MyClass();
Then x is a treasure map, and new MyClass() is 'create a new treasure chest and bury it in the sand'. The = in the middle says: Update the treasure map named x, so that following it would lead you to the treasure I just made (new X() means: Make new treasure and bury it).
MyClass x = null;
means you have a treasure map named x which is currently blank.
If not, is there a way for me to create the object so that all three instance variables are null?
That would imply a treasure chest of the MyClass treasure type, which has room for some scratches (int a - a number), and which contains a treasure map (the String b variable). If you want to set them all to null, well, you can't - a is a primitive (int) and those aren't treasure maps, they are the actual number. You can't not have one - a cannot be null. At best, a can be 0. b CAN be null. That means there's real treasure, but the treasure contains yet another treasure map (in java it's mostly treasure maps all the way), but that one is blank. That's different from there being no treasure at all.
More generally, the question: "Can I make a new instance of MyClass such that all fields are some value I desire" is the wrong question to ask, perhaps: The general principle is encapsulation: MyClass is an API: It's like the receptionist at a big corp's office. The receptionist decides what services are available. Even if the CEO is available, if the receptionist elects not to answer the question 'can I see the CEO right now please?', then you can't see her.
Your question boils down to: "If I storm into this office and I demand to speak to the CEO, will I be allowed to?" - the only viable answer is: Well, the receptionist would decide, so you'd have to ask him. For classes: Whatever the API lets you do, you can do. But that's all you can do.
If there is no constructor that initializes these fields to null, then, no, you can't.
What is the difference between an object, instance, and reference? They say that they have to create an instance to their application? What does that mean?
An object and an instance are the same thing.
Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".
A reference either refers to a specific object or else it can be a null reference.
They say that they have to create an instance to their application. What does it mean?
They probably mean you have to write something like this:
Foo foo = new Foo();
If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()). For example there is the class Car, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null; - s is a reference, that currently references no instance, but can reference an instance of the String class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.
The new operator instantiates a
class by allocating memory for a new
object and returning a reference to
that memory.
Note: The phrase "instantiating a class" means the same thing as
"creating an object." When you create
an object, you are creating an
"instance" of a class, therefore
"instantiating" a class.
Take a look here
Creating Objects
The types of the Java programming
language are divided into two
categories: primitive types and
reference types.
The reference types
are class types, interface types, and
array types.
There is also a special
null type.
An object is a
dynamically created instance of a
class type or a dynamically created
array.
The values of a reference
type are references to objects.
Refer Types, Values, and Variables for more information
I think that Object = Instance. Reference is a "link" to an Object.
Car c = new Car();
variable c stores a reference to an object of type Car.
Computer c= new Computer()
Here an object is created from the Computer class. A reference named c allows the programmer to access the object.
The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.
This statement will just allot memory for the static meber variables, not for the normal member variables.
But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.
basically object and instance are the two words used interchangeably.
A class is template for an object and an object is an instance of a class.
"creating an instance of a class" how about, "you are taking a class and making a new variable of that class that WILL change depending on an input that changes"
Class in the library called Nacho
variable Libre to hold the "instance" that will change
Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in "Libre" on the left side of the equals sign (you know "Nacho Libre = new Nacho(Scanner.in)" "Nacho Libre" is on the left of the = (that's not tech talk, that's my way of explaining it)
I think that is better than saying "instance of type" or "instance of class". Really the point is it just needs to be detailed out more.... "instance of type or class" is not good enough for the beginner..... wow, its like a tongue twister and your brain cannot focus on tongue twisters very well.... that "instance" word is very annoying and the mere sound of it drives me nuts.... it begs for more detail.....it begs to be broken down better. I had to google what "instance" meant just to get my bearings straight..... try saying "instance of class" to your grandma.... yikes!
The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.
Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.
class A
{
int x=0;
public static void main(String [] args)
{
int y=0;
y=y+1;
x=x+1;
}
}
Let us compile and run this code.
step 1: javac A.class (.class file is generated which is byte code)
step 2: java A (.class file is converted into executable code)
During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).
So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.
This is done through creating the Object and the keyword NEW does this Job.
"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "
Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.
-Definition taken from the book "Sams Teach Yourself Java in 21 days".
Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.
This is a very simple and basic way to do it:
public MainClass() /*******this is the constructor of MainClass*******/
{
Class_2 nameyouwant = new Class_2();
}
I hope this helps!
Instance variable: It must be attached to the object. Instance variables in this class can only be used after instantiating the class
public class Test{
static int a = 13;
int b = 14;
public static void main(String[] args){
int d = new Test().b;
System.out.println(d);
}
}
Instance = memory is allocated at run time for anything that is called instance
Object = memory is allocated at run time for class that is called object
I've been given a coursework assignment where I have to build a prototype hotel booking system, in accordance with the specification, which is as follows:
You will need at least three classes:
Hotel
This should store all the essential information about a hotel,
including a name and some rooms.
Room
This should store the number of beds in a room.
Bed
This should store the size of a bed (i.e. single or double).
I'm totally confused about where to start!
I was under the impression that objects could not be contained within other objects.
For example, let's assume we instantiate a "Hotel" object. How would we then instantiate "Room" objects, and within that object, "Bed" objects?
How are these objects being stored? How do we interact with them indirectly, from another object?
Typically you don't need to nest classes into other classes, which are called inner classes, unless the work that a class takes care of can be chunked into small units that never need to be known outside it's parent class.
It sounds like the concept you want to look into is Composition. It's when an object holds a reference to another object.
public class Room {
private boolean isVacant;
public Room() {
isVacant = true; // The room starts vacant
}
// Pretend there is a way for clients to check in and out of the room
public boolean isVacant() {
return isVacant;
}
}
public class Hotel {
// Using composition, I can make an instance of one class
// available to the methods of another
private Room room101;
public Hotel(Room room101) {
this.room101 = room101;
}
public boolean isRoom101Vacant() {
return room101.isVacant();
}
}
Our hotel may not be very useful having only one room, but this example shows how you can "compose" one object into another. Methods of Hotel can now use methods of it's Room instance known as room101. You will want to think about how your rooms are structured, and how you want to represent it within your Hotel class. A few objects used to store collections of other objects include ArrayList and HashMap.
Edit:
this is a fairly difficult concept to understand before you understand what a class is compared to an instance of that class (an object). In the constructor of my sample Hotel class, I have a variable of type Room called room101. And outside of the constructor is an instance field of the same type and name.
Java will always refer to a variable or reference of the nearest scope. So if I have a method reference called room101, how can I refer to that other one declared outside the constructor, at instance level? That's where this comes in.
public class ThisExample {
// This is a separate variable at the instance level
// Lets call this global in the comments
private int a;
public ThisExample() {
// This is a separate variable in the method level,
// lets call this local in the comments
int a;
a = 5; // our local is now assigned 5
this.a = 10; // Our global is now assigned 10
this.a = a; // our global is now assigned to 5
a = this.a * 2; // our local is now assigned to 10
}
}
In short, this refers to "this" instance of a class. It's a way for an instance of a class to refer to itself as if from the outside. Just like how another object would refer to room101's method as room101.isVacant(). A method in the Room class would similarly do this.isVacant() for the same effect.
And as a final note, if there is only one declaration of a symbol within a class. The this keyword is implied. So Room can call it's own method just as well without it as long as there is no other conflicting symbols of the same name. (This doesn't occur with methods as much as with instance fields/local variables)
Hopefully this helps clear things up a bit!
Your assignment is how to model some real world concepts into code.
It appears that the core of your problem can be stated as a Guest can book a Room.
I don't want to do your work for you, so let me start by asking how you would write that in code? After that, we can address the "Hotel" and "Bed". Is this a major assignment or just a quick question? Your implementation would depend on this.
A rule to learn and apply is:
An action on an object in the real world, becomes a method of that object in an Object Oriented approach.
What is the difference between an object, instance, and reference? They say that they have to create an instance to their application? What does that mean?
An object and an instance are the same thing.
Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".
A reference either refers to a specific object or else it can be a null reference.
They say that they have to create an instance to their application. What does it mean?
They probably mean you have to write something like this:
Foo foo = new Foo();
If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()). For example there is the class Car, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null; - s is a reference, that currently references no instance, but can reference an instance of the String class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.
The new operator instantiates a
class by allocating memory for a new
object and returning a reference to
that memory.
Note: The phrase "instantiating a class" means the same thing as
"creating an object." When you create
an object, you are creating an
"instance" of a class, therefore
"instantiating" a class.
Take a look here
Creating Objects
The types of the Java programming
language are divided into two
categories: primitive types and
reference types.
The reference types
are class types, interface types, and
array types.
There is also a special
null type.
An object is a
dynamically created instance of a
class type or a dynamically created
array.
The values of a reference
type are references to objects.
Refer Types, Values, and Variables for more information
I think that Object = Instance. Reference is a "link" to an Object.
Car c = new Car();
variable c stores a reference to an object of type Car.
Computer c= new Computer()
Here an object is created from the Computer class. A reference named c allows the programmer to access the object.
The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.
This statement will just allot memory for the static meber variables, not for the normal member variables.
But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.
basically object and instance are the two words used interchangeably.
A class is template for an object and an object is an instance of a class.
"creating an instance of a class" how about, "you are taking a class and making a new variable of that class that WILL change depending on an input that changes"
Class in the library called Nacho
variable Libre to hold the "instance" that will change
Nacho Libre = new Nacho(Variable, Scanner Input, or whatever goes here, This is the place that accepts the changes then puts the value in "Libre" on the left side of the equals sign (you know "Nacho Libre = new Nacho(Scanner.in)" "Nacho Libre" is on the left of the = (that's not tech talk, that's my way of explaining it)
I think that is better than saying "instance of type" or "instance of class". Really the point is it just needs to be detailed out more.... "instance of type or class" is not good enough for the beginner..... wow, its like a tongue twister and your brain cannot focus on tongue twisters very well.... that "instance" word is very annoying and the mere sound of it drives me nuts.... it begs for more detail.....it begs to be broken down better. I had to google what "instance" meant just to get my bearings straight..... try saying "instance of class" to your grandma.... yikes!
The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.
Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.
class A
{
int x=0;
public static void main(String [] args)
{
int y=0;
y=y+1;
x=x+1;
}
}
Let us compile and run this code.
step 1: javac A.class (.class file is generated which is byte code)
step 2: java A (.class file is converted into executable code)
During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).
So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.
This is done through creating the Object and the keyword NEW does this Job.
"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "
Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.
-Definition taken from the book "Sams Teach Yourself Java in 21 days".
Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.
This is a very simple and basic way to do it:
public MainClass() /*******this is the constructor of MainClass*******/
{
Class_2 nameyouwant = new Class_2();
}
I hope this helps!
Instance variable: It must be attached to the object. Instance variables in this class can only be used after instantiating the class
public class Test{
static int a = 13;
int b = 14;
public static void main(String[] args){
int d = new Test().b;
System.out.println(d);
}
}
Instance = memory is allocated at run time for anything that is called instance
Object = memory is allocated at run time for class that is called object
Example 1
/**
*Program Name: Cis36L0411.java
*Discussion: Class -- Data Members ONLY
* Method Members ONLY
*/
class Cis36L0411
{
public static void main( String[] args )
{
DataOnly data1 = new DataOnly();
System.out.println( "DataOnly\tLIMIT\t\t" + data1.LIMIT );
System.out.println( "\t\tintMem\t\t" + data1.iMem );
System.out.println( "\t\tdoubleMem\t" + data1.dMem );
MethodOnly method1 = new MethodOnly();
method1.printFunc( 5 );
method1.printFunc( "MethodOnly object!" );
method1.printFunc( data1.LIMIT );
return;
}
}
class DataOnly
{
final int LIMIT = 100; //constant and package mode or access
int iMem; //package mode or access
double dMem; //package mode or access
}
class MethodOnly
{
void printFunc( int iA ) //package mode or access
{
System.out.println( "The int value is " + iA );
return;
}
public void printFunc( String str ) //public mode or access
{
System.out.println( "The String is printed from " + str );
return;
}
}
I went to this site and I read it, but I am still confused.
DataOnly data1 = new DataOnly(); I know this line creates an object. But can someone break this line down for me? What does each word do? DataOnly is the class? type? data1 is the variable? I think new DataOnly is a reference to a location. And the () is the variables in the location? Am I correct?
How did they print data1.LIMIT, data1.iMem, Data1.dMem? Did they print it by looking at the location of DataOnly()? Does DataOnly() reference class DataOnly?
I'm just completely lost on the whole process of the MethodOnly object.
1) DataOnly data1 = new DataOnly(); I
know this line creates an object. But
can someone break this line down for
me? What does each word do? DataOnly
is the class?type? Data1 is the
variable? I think new DataOnly is a
reference to a location. And the () is
the variables in the location? Am I
correct?
The line means create a variable named "data1" of the type DataOnly. Then create a new object of type "DataOnly" and make the variable point to it.
2) How did they print data1.LIMIT,
data1.iMem, Data1.dMem? Did they print
it by looking at the location of
DataOnly()? Does DataOnly() reference
class DataOnly?
DataOnly is just the template for an object (a class). The print is using an object in memory created from that template to print the values.
3) I'm just completely lost on the
whole process of the MethodOnly
object.
Objects can contain both data and perform functions depending on the tempate (class) it was created from. The MethodOnly class appears to be defined to only contain code and no data. The DataOnly class seems to be defined to just store values and not do any actions.
Summary
I think the easiest way to think of it is that the class is the blue-print for an object. Objects are created (using the "new" keyword) based on these blueprints and stored in memory. So all your work will be done with objects, you just use the classes to tell it what type of object you want.
Because we are talking about very basic object orientated principals here, I'm going to ignore picking apart the example given. Look at it this way - you have 5 basic concepts to understand:
Class - A class in (as stated by JohnFx) a blue print for something. An analogy would be a blue print for your house. It describes how the house will look if built, how it will be heated or cooled, the number of bedrooms etc.
Object - A Object is what you get when you alloc some memory space and the set it up based on a specific Class. The word Instance is often used in this context. i.e. "an Instance of a class". It effectively means the same thing.
So, from the house blue print (Class) we can now build a house (Object). You can have many Objects (instances) created from a single blue print (Class). For example, every house in the street might be created from the same blue print. "new MethodOnly()" is an example how your create a object from a class in java.
Variable - a Variable is something that points to an object and is how you find it when you need to do something. i.e. if you want to sleep in your house, you need to find your house first. Your street address (variable) is what you look up to find the house. Every house in the street will have it's own unique street address.
In addition, you can have multiple variables all pointing to the same object. i.e. If you have your street address to your house in a note book, you can write a copy of it and give it to someone else so they can come over for a party. Now there are two (variables) notes, both pointing at the same house.
There are effective two types of variables you will encounter. One for refering to objects as just discussed. And the other for containing single values. Usually numbers. These are called Primitive Variables because they do not refer to Objects created from Classes.
Methods - Methods are things that class can do. For example void printFunc( int iA ) {...} in your code is an example of a method. It does something. In our house analogy, you can press the door bell to alert someone you are at the front door. This is a method: void RingDoorBell().
Property - Lastly there are properties. These look and smell like variables and they are. Why they are regarded differently is because they are declared as part of the Class "blue print". Your DataOnly class is an example which contains 3 primitive variable Properties.
Properties are one of the things that make Object Orientation work. Going back to our houses, each house (Object/Instance) in the street might have come from the same blue print (Class), but they all look different. Different colours, number of bedrooms etc. The colour and number of bedrooms are the Properties of the House class. By giving them different values when the houses are built (Instantiated), we create variation.
It's also possible, just like people repainting their house a different colour, to change the value of a property. It will stay set to that value as long as the house (Object) exists.
Lots of concepts in this example. It might be wise to look at more simple ones. But I'll try to explain.
First question:
Let's look at this first:
class DataOnly
{
final int LIMIT = 100; //constant and package mode or access
int iMem; //package mode or access
double dMem; //package mode or access
}
This is a class. Think of it as a blueprint that can be used to create objects. (More accurately, blueprints should be called types). It's important to understand that a class itself is not the object. We can create several objects with the same type.
DataOnly data1 = new DataOnly();
You are right, this line creates an object. DataOnly is a type, and data1 is a reference (more on that later). DataOnly data1 means that data1 will be a reference to an object that is created to match the type DataOnly. new DataOnly means that we are creating an object using that "blueprint" we defined. Where will the object be? It will be stored somewhere in the memory, and our reference data1 will hold that location in the memory (memory address) for us. Whenever we want to do something with our object, we use this reference to reach it in the memory. We could create a data2 object, which would be placed somewhere else in the memory, and change its members. They would not affect data1 in any way, because the class is the "blueprint", the object is the thing we created using that blueprint.
The () means that we are calling a parameterless constructor.
For your second question: if you understand my previous explanation, then this one should be no problem. We want to do something with object - print its members. Ok, we have our reference. The . (dot) is used to access parts of the object. data1.LIMIT will eventually mean that we take the object referenced by data1 and look at the LIMIT member of it.
Third question: Objects can not only hold information but can also do things. For example, you probably used a CD player before. If you look at it, you can see how many tracks the current CD has. But not only that, you can push the play button and it will play the song for you. Let's see how that would look in Java.
class CDPLayer
{
public int numberOfTracks = 12;
public void play()
{
System.out.println("I'm playing! Yay!");
}
}
This is a simple CD player, and there is no way to change the CD in it :)
The things an object has are its members, the things it can do are its methods. Our very simple CD Player has a number of tracks and can do playing. Methods and members are equally parts of the object, so we can use both with the dot . to reach them. (remember, an object is not the same as the class)
At this point you will probably understand the following code:
CDPlayer player = new CDPlayer();
System.out.println("The number of tracks is " + player.numberOfTracks);
player.play();
We create a CDPlayer and then print the number of tracks in it. We then use its play method.
In your example, the MethodOnly class declares two methods with the same name. This is probably confusing, but the compiler does not determine which method to use by name, but by signature. The signature of the method includes its return type, its name, and all of its parameters. What happens when you call printFunc? The compiler looks at the type of the arguments you passed, and will do it's best to find the method that matches that.
The first time it is called with an argument 5, which is an integer, or int for short. The compiler selects the printFunc with the int parameter
Second time it is called with a "string literal" so the compiler selects the printFunc with the String parameter
Third time it is called with a variable. Which variable is it? It's data1's LIMIT member. We go and check the blueprint to see its type: final int. final is tricky and might mean different things in different contexts. This time it means that the variable can only be set once during the program and cannot be changed later. So now what? Which printFunc does the compiler choose? There is no final int version. As I said before, the compiler tries to find the best one, and in this case, a simple int parameter is good enough. If it can't find a good enough match, it will stop and print an error message.
DataOnly is the type of object.
Data1 is the object.
new Data() is calling the constructor of the object, which basically allocates a new spot in memory for the object as well as runs any code in the constructor.
1) DataOnly data1 = new DataOnly();
DataOnly is like a variable type. Think like String data1, but instead it is a class you created. data1 is an object of type DataOnly. new is used to say make a new instance of this class. DataOnly() is the constructor. That is, it tells the computer to make the object.
2) LIMIT, iMem, & dMem are variables inside of data1. You could just as easily say data1.LIMIT = 9000; It is just accessing the variables inside of the object data1.
3) Method only is an object that uses methods. A method is just another name for a function, but it is inside the object. Standard practice is to access and change variables of an object via methods instead of directly accessing the variable:
public class Methods {
public int getVariable() {
return variable;
}
public void setVariable(int i) {
variable = i;
}
private int variable;
}
If you didn't know, private is used to make a variable visible to the methods in an object, but nothing outside of the object. In that case, you couldn't call System.out.println(data1.variable); You would have to use the method getVariable.
Hope this clears things up.
This is a really unnatural sort of example. The purpose of a class is to provide a template for creating objects. An object is a set of data packaged together with methods that operate on that data.
Yes, data1 is the variable. new DataOnly() allocates memory for an object (setting aside space for the variables listed) using DataOnly as the template for it. data1 is the reference to the spot where the object is stored, so data1.iMem refers to the field iMem that is part of the object referenced by data1.
As for the MethodOnly thing, that's an example of an object that has methods. In this example the methods are just functions you can call, but because they are defined as instance methods you need to instantiate an object of type MethodOnly before you can call the method. In this case it would make more sense if there were instance variables declared for the class--the idea of an instance method is that a reference to the instance is passed into the method implicitly so that your method can access the instance variables for that object, so here it must seem like a strange technicality to have to create an object to call the method, and it's not surprising that you're confused.
Basically, the keyword new followed by a type name and parens is allocating memory, then setting the variable on the left-hand side to a pointer to that memory location.
1) DataOnly data1 = new DataOnly(); I know this line creates an object.
But can someone break this line down for me? What does each word do?
DataOnly = name of the class whose variable you want.
DataOnly data1 = declaration of a variable called data1 of type DataOnly
new = keyword used for instantiating objects of a type (instantiation = creation)
new DataOnly() = instantiates a object of type DataOnly i.e allocates memory on the heap as per DataOnly type's definition and returns a reference to this "instance" which is what data1 will be pointing to.
DataOnly() = the default contructor of type DataOnlythat is called at time of creation
2) How did they print data1.LIMIT, data1.iMem, Data1.dMem?
Did they print it by looking at the location of DataOnly()?
Does DataOnly() reference class DataOnly?
After the construction, data1 variable is pointing to a location where memory has been reserved for an object of type DataOnly i.e an object with LIMIT, iMem and dMem member variables.
So, when you do data1.LIMIT in your code, think of data1 as the base memory address of the object and doing .LIMIT will offset it by the appropriate value to get to the space reserved for LIMIT variable in that object.
Same applies for iMem and dMem.
The logic for offsetting and reaching the correct memory location to get the value etc is all invisible to the programmer
3) I'm just completely lost on the whole process of the MethodOnly object
MethodOnly is actually a class and not an object
MethodOnly method1 = new MethodOnly();
After the above statement, method1 is the object of type MethodOnly.
MethodOnly class is more like a Utility class as it does not have any data of its own.
It sole purpose is to take inputs via its 2 methods of type int / string and print them out.
in this code:
DataOnly data1 = new DataOnly();
The first DataOnly is the type, data1 is the object-specific name. new DataOnly() just means that you're setting data1 to a new instance of the DataOnly class. The "()" designate arguments, in this case none, to be sent to the constructor function to modify the specific instance, data1, of DataOnly.
I don't quite understand your second question.
Hope this helps.
You might want to look through the Java Trails. In particular, the Learning the Java Language trail starts with a decent overview of objects and classes as used in Java.