开发者

I'm having a hard time understanding Java objects and classes

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 printFu开发者_如何学JAVAnc( 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.

  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?

  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?

  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜