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.
Related
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
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Noob here, with some questions about fundamental things in Java.
If we have a class Person with a constructor (also Person) we can create a reference variable like this:
Person johnny = new Person();
Let's say we have just created in a class People an object, johnny.
It holds an "address" to where the object and its values are kept, unlike objects of primitives types do (e.g. int x = 5; has the value 5, johnny is a "link" to the value - if I've understood things correctly.)
1st word: Person is a class/type (<-- edited here), but:
What does a class/type do? What does it entail? Perhaps: what does a type do, if it is not a 'primitive type'?
2nd word: johnny is a reference variable, of type Person.
- If I am missing something, please enlighten me :)
3rd word: new this just states that we are creating the new object.
4th word: second Person:
This is the object we are creating?
Is this the constructor or the class we are referring to?
ALSO:
The value (address) that the variable is referring to is everything after the equal sign? Is the address new Person?
LASTLY: Polymorphism.
So if we have a sub-class Adult, which extends the super-class Person, then we can do this:
Person amanda = new Adult();
What are we doing now?
Is amanda of class type Person and refers to an object in the class Adult?
Thanks for your help :)
1st word: 'Person' is a class type
Yes, but it might just as well be a primitive type, does not matter for that "first word" which is the type declaration for the variable.
Another example would be
int a = 1;
When you declare a variable or parameter in Java, the name is preceded by the type.
2nd word: 'johnny' is a reference variable, of type Person
That's right. You name your variable johnny here. And its type is what you specified for it right in front of the name.
3rd word: 'new' this just states that we are creating the new object.
new means that we are calling a constructor (of the class that is following the new). That is indeed how you create objects in Java.
4th word: second 'Person
That is the name of the class that you are calling the constructor of. This will always return a new instance of exactly that class (not of a subclass). There can be more than one constructor to choose from for a given class, they are differentiated by parameter counts and types (in your case, a constructor without any parameters).
The value (address) that the variable is referring to is everything after the equal sign? The address is 'new Person'?
new Person() returns a reference to the newly created object instance. It will be stored in your variable johnny.
LASTLY: Polymorphism.
Your Adult class is a subclass of Person. This means that you can use it in all situations where a Person would be required. In particular, you can assign it to a Person-type variable (such as johnny) and call all Person methods on it.
This is all too confused for words.
When creating a reference type, what are we exactly doing?
Nothing. There is no such operation in Java.
When we have a class (or super-class, I'll get back to that) Person with a constructor (also Person) we can create a reference type like this:
No you can't. What you are creating here is a reference. You are not creating a type, let alone a 'reference type'.
Person johnny = new Person();
We have just created in a new class People (e.g.) an object, johnny.
I see no evidence of a class People, but I'll take your word for it.
It holds an "address" to where the object and its values are kept, unlike objects of primitives types do (e.g. int x = 5; has the value 5, johnny is a "link" to the value - if I've understood things correctly.)
Correct.
1st word: 'Person' is a class type, but:
No it isn't. Person is a class. Period.
What does a class type do? What does it entail?
Nothing because it doesn't exist. A class on the other hand is a kind of template for constructing objects from, that determines its data members and what code can be called on it.
Perhaps: what does a type do, if it is not a 'primitive type'?
It extends the type system beyond the primitive types, in a way which can be reasoned about and computed, via inheritance, interface implementation, and the Liskov substituion principle (q.v.).
2nd word: 'johnny' is a reference variable, of type Person. - If I am missing something, please enlighten me :)
Correct.
3rd word: 'new' this just states that we are creating the new object.
Correct.
4th word: second Person: This is the object we are creating?
This is the class (or 'type' if you insist) of the object we are creating.
Is this the constructor or the class we are referring to?
Both. The arguments or lack of them determine which constructor is called. The name of the constructor is the same as the name of the class, by the rules of Java.
The value (address) that the variable is referring to is everything after the equal sign? The address is 'new Person'?
The variable refers to the object that was created. There is no concept of 'address' in Java.
LASTLY: Polymorphism. So if we have a sub-classes 'Adult', which extends the super-class 'Person', then we can do this:
Person amanda = new Adult();
What are we doing now?
You are creating an object of type Adult and referring to it via a reference of type Person, which can only succeed if Person is a base class of or an interface implemented by Adult.
Is 'amanda' of class type Person
'amanda' is a reference of type/class Person.
and an object in the class 'Adult'?
amanda isn't an object at all. The object it refers to is an object of class Adult.
I'm creating a program that has creatures battle each other. I have a class called Creature, which takes integer inputs for attack, speed, and health, respectively.
Whenever I try to make a new instance of the Creature class, and try to reference it using methods, it thinks I'm talking about the newest instance of the class.
Creature c = new Creature(1,2,3);
c.getStats();
This prints out Attack: 1 Speed: 2 Health: 3
However, if I create a new Creature...
Creature c = new Creature(1,2,3);
c.getStats();
Creature b = new Creature(9,9,9);
c.getStats();
As you can see, I'm referencing the same creature twice. But, I get different results. Even if I specifically state the creature I'm talking about is c, it'll go for the newest instance of the Creature class instead. I believe what's happening is that Java is replacing c's variables with. What can I do to fix this?
Your problem is clearly on the line of code that you instantiate (create) the second Creature object called b. Since you didn't post your constructor for Creature, I guess in the constructor you assigned the values passed in to a static variable. Every class has one static variable per application domain.
So that's why you get different results. Static variables change no matter which object you call on. Thus, calling the constructor the second time will overwrite the value that you just assigned to the static variable.
Now you can try creating another Creature and call
c.getStats()
again and you will see different results.
To solve this, you need to go into your Creature class and look for the variables that stores the stats of the creatures. There should be a word "static". And you should delete that.
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.