简体   繁体   English

我很难理解Java对象和类

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

Example 1 例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. 我去了这个网站 ,我读了它,但我仍然感到困惑。

  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? DataOnly是什么类? type? 类型? data1 is the variable? data1是变量? I think new DataOnly is a reference to a location. 我认为new DataOnly是对位置的引用。 And the () is the variables in the location? 并且()是位置的变量? Am I correct? 我对么?

  2. How did they print data1.LIMIT , data1.iMem , Data1.dMem ? 他们是如何打印data1.LIMITdata1.iMemData1.dMem Did they print it by looking at the location of DataOnly() ? 他们是通过查看DataOnly()的位置来DataOnly()吗? Does DataOnly() reference class DataOnly ? DataOnly()引用类DataOnly吗?

  3. I'm just completely lost on the whole process of the MethodOnly object. 我完全迷失在MethodOnly对象的整个过程中。

1) DataOnly data1 = new DataOnly(); 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? DataOnly是类?类型? Data1 is the variable? Data1是变量? I think new DataOnly is a reference to a location. 我认为新的DataOnly是对位置的引用。 And the () is the variables in the location? 并且()是位置的变量? Am I correct? 我对么?

The line means create a variable named "data1" of the type DataOnly. 该行意味着创建一个名为“data1”的变量,类型为DataOnly。 Then create a new object of type "DataOnly" and make the variable point to it. 然后创建一个“DataOnly”类型的新对象,并使变量指向它。

2) How did they print data1.LIMIT, data1.iMem, Data1.dMem? 2)他们是如何打印data1.LIMIT,data1.iMem,Data1.dMem的? Did they print it by looking at the location of DataOnly()? 他们是通过查看DataOnly()的位置来打印的吗? Does DataOnly() reference class DataOnly? DataOnly()引用类DataOnly吗?

DataOnly is just the template for an object (a class). DataOnly只是对象(类)的模板。 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. 3)我完全迷失在MethodOnly对象的整个过程中。

Objects can contain both data and perform functions depending on the tempate (class) it was created from. 对象可以包含数据和执行函数,具体取决于创建它的tempate(类)。 The MethodOnly class appears to be defined to only contain code and no data. MethodOnly类似乎被定义为仅包含代码而不包含数据。 The DataOnly class seems to be defined to just store values and not do any actions. DataOnly类似乎被定义为仅存储值而不执行任何操作。

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. 基于这些蓝图创建对象(使用“new”关键字)并存储在内存中。 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: 以这种方式看待它 - 您有5个基本概念需要理解:

  • Class - A class in (as stated by JohnFx) a blue print for something. 类 - 在(如JohnFx所述)的类中,用于某事的蓝图。 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. Instance这个词经常用在这个上下文中。 ie "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). 因此,从房子蓝图(Class)我们现在可以建造房屋(Object)。 You can have many Objects (instances) created from a single blue print (Class). 您可以从单个蓝图(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. “new MethodOnly()”是一个如何从java中的类创建对象的示例。

  • Variable - a Variable is something that points to an object and is how you find it when you need to do something. 变量 - 变量是指向对象的东西,是您在需要做某事时找到它的方式。 ie 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. 此外,您可以将多个变量都指向同一个对象。 ie 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. 例如,代码中的void printFunc( int iA ) {...}是方法的示例。 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() . 这是一个方法: 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. 您的DataOnly类是一个包含3个基本变量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. 回到我们的房子,街道上的每个房子(物体/实例)都可能来自同一个蓝图(Class),但它们看起来都不一样。 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是一个引用(稍后将详细介绍)。 DataOnly data1 means that data1 will be a reference to an object that is created to match the type DataOnly . DataOnly data1表示data1将是对与DataOnly类型匹配的对象的引用。 new DataOnly means that we are creating an object using that "blueprint" we defined. new DataOnly意味着我们使用我们定义的“蓝图”创建对象。 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. 它将存储在内存中的某个位置,我们的引用data1将为我们保存在内存中的位置(内存地址)。 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. 我们可以创建一个data2对象,它将被放置在内存中的其他位置,并更改其成员。 They would not affect data1 in any way, because the class is the "blueprint", the object is the thing we created using that blueprint. 它们不会以任何方式影响data1,因为类是“蓝图”,对象是我们使用该蓝图创建的对象。

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. 我们想用object做某事 - 打印其成员。 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. data1.LIMIT最终意味着我们接受data1引用的对象并查看它的LIMIT成员。

Third question : Objects can not only hold information but can also do things. 第三个问题 :对象不仅可以保存信息,还可以做事情。 For example, you probably used a CD player before. 例如,您之前可能使用过CD播放器。 If you look at it, you can see how many tracks the current CD has. 如果你看一下,你可以看到当前CD有多少曲目。 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. 让我们看看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 :) 这是一个简单的CD播放器,没有办法改变它的CD :)

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. 我们非常简单的CD播放器有很多曲目,可以播放。 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. 我们创建一个CDPlayer然后打印其中的轨道数。 We then use its play method. 然后我们使用它的play方法。

In your example, the MethodOnly class declares two methods with the same name. 在您的示例中,MethodOnly类声明两个具有相同名称的方法。 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 ? 调用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. 第一次用参数5调用它,它是一个整数,或简称为int。 The compiler selects the printFunc with the int parameter 编译器使用int参数选择printFunc

Second time it is called with a "string literal" so the compiler selects the printFunc with the String parameter 第二次使用“字符串文字”调用它,因此编译器选择带有String参数的printFunc

Third time it is called with a variable. 第三次使用变量调用它。 Which variable is it? 它是哪个变量? It's data1's LIMIT member. 它是data1的LIMIT成员。 We go and check the blueprint to see its type: final int . 我们去查看蓝图以查看其类型: final int final is tricky and might mean different things in different contexts. final是棘手的,在不同的语境中可能意味着不同的东西。 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? 编译器选择哪个printFunc? There is no final int version. 没有final int版本。 As I said before, the compiler tries to find the best one, and in this case, a simple int parameter is good enough. 正如我之前所说,编译器试图找到最好的一个,在这种情况下,一个简单的int参数就足够了。 If it can't find a good enough match, it will stop and print an error message. 如果找不到足够好的匹配,它将停止并打印错误消息。

in this code: 在这段代码中:

DataOnly data1 = new DataOnly();

The first DataOnly is the type, data1 is the object-specific name. 第一个DataOnly是类型, data1是特定于对象的名称。 new DataOnly() just means that you're setting data1 to a new instance of the DataOnly class. new DataOnly()只是意味着您将data1设置为DataOnly类的新实例。 The " () " designate arguments, in this case none, to be sent to the constructor function to modify the specific instance, data1 , of DataOnly . () ”指定参数,在这种情况下为none,将被发送到构造函数以修改DataOnly的特定实例data1

I don't quite understand your second question. 我不太明白你的第二个问题。

Hope this helps. 希望这可以帮助。

DataOnly is the type of object. DataOnly是对象的类型。

Data1 is the object. Data1是对象。

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. new Data()调用对象的构造函数,它基本上为对象分配内存中的新点,并在构造函数中运行任何代码。

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. 是的,data1是变量。 new DataOnly() allocates memory for an object (setting aside space for the variables listed) using DataOnly as the template for it. new DataOnly()使用DataOnly作为模板为对象分配内存(为列出的变量留出空间)。 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. data1是对存储对象的位置的引用,因此data1.iMem指的是作为data1引用的对象的一部分的字段iMem。

As for the MethodOnly thing, that's an example of an object that has methods. 对于MethodOnly事物,这是一个具有方法的对象的示例。 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. 在此示例中,方法只是您可以调用的函数,但由于它们被定义为实例方法,因此您需要在调用方法之前实例化MethodOnly类型的对象。 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. 基本上,关键字new后跟类型名称和parens是分配内存,然后将左侧的变量设置为指向该内存位置的指针。

1) DataOnly data1 = new DataOnly(); 1)DataOnly data1 = new DataOnly();
DataOnly is like a variable type. DataOnly就像一个变量类型。 Think like String data1, but instead it is a class you created. 像String data1一样思考,但它是你创建的一个类。 data1 is an object of type DataOnly . data1DataOnly类型的对象。 new is used to say make a new instance of this class. new用于表示创建此类的新实例。 DataOnly() is the constructor. DataOnly()是构造函数。 That is, it tells the computer to make the object. 也就是说,它告诉计算机制作该对象。

2) LIMIT, iMem, & dMem are variables inside of data1. 2)LIMIT,iMem和dMem是data1中的变量。 You could just as easily say data1.LIMIT = 9000; 你可以很容易地说data1.LIMIT = 9000; It is just accessing the variables inside of the object data1 . 它只是访问对象data1的变量。

3) Method only is an object that uses methods. 3)方法只是一个使用方法的对象。 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. 如果您不知道,private用于使变量对对象中的方法可见,但对象外部没有任何内容。 In that case, you couldn't call System.out.println(data1.variable); 在这种情况下,您无法调用System.out.println(data1.variable); You would have to use the method getVariable . 您必须使用方法getVariable

Hope this clears things up. 希望这可以解决问题。

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 =您想要的变量类的名称。

DataOnly data1 = declaration of a variable called data1 of type DataOnly DataOnly data1 =可变称为声明data1类型DataOnly

new = keyword used for instantiating objects of a type (instantiation = creation) new =用于实例化类型对象的关键字(instantiation = creation)

new DataOnly() = instantiates a object of type DataOnly ie 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. new DataOnly() =实例化DataOnly类型的对象,即根据DataOnly类型的定义在堆上分配内存,并返回对此“实例”的引用,这是data1将指向的内容。

DataOnly() = the default contructor of type DataOnly that is called at time of creation DataOnly() =在创建时调用的DataOnly类型的默认构造DataOnly

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 ie an object with LIMIT, iMem and dMem member variables. 构造之后,data1变量指向为DataOnly类型的对象保留内存的位置,即具有LIMIT,iMem和dMem成员变量的对象。

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. 因此,当您在代码中执行data1.LIMIT ,请将data1视为对象的基本内存地址,然后执行.LIMIT将使用适当的值抵消它以获取为该对象中的LIMIT变量保留的空间。

Same applies for iMem and dMem. 同样适用于iMem和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实际上是一个类而不是一个对象

MethodOnly method1 = new MethodOnly();

After the above statement, method1 is the object of type MethodOnly. 在上面的语句之后, method1是MethodOnly类型的对象。

MethodOnly class is more like a Utility class as it does not have any data of its own. MethodOnly类更像是一个Utility类,因为它没有自己的任何数据。 It sole purpose is to take inputs via its 2 methods of type int / string and print them out. 它的唯一目的是通过类型为int / string的2种方法获取输入并将其打印出来。

You might want to look through the Java Trails . 您可能希望查看Java Trails In particular, the Learning the Java Language trail starts with a decent overview of objects and classes as used in Java. 特别是, 学习Java语言跟踪的开头是对Java中使用的对象和类的体面概述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我只是很难从我的 Java 课程中理解课程材料 - I'm just having hard time understanding the class material from my java class 我很难理解和实现构造函数,我正在寻找一些指导 - I'm having a hard time understanding and implementing a constructor and I'm looking for some guidance 需要在 Java 中解析输入的指导,需要专门使用类,很难理解构造函数 - Need Guidance on Parsing an Input in Java, Need to Specifically Use Classes, having a Hard time understanding Constructors 所以我很难理解什么时候使用静态以及什么时候从函数头中排除它 - So I'm having a hard time understanding when to use static and when to exclude it from function headers 在Java中使用泛型类和泛型方法很难 - Having a hard time with generic classes and generic methods in java 我很难在JavaFX中调整某些元素的大小 - I'm having a hard time getting some elements to resize in JavaFX 我在实现链接列表类时遇到了困难 - I'm having a hard time implementing my linked list class 我很难从第一帧开始调用变量 - I'm having a hard time calling the variable from first frame 我很难启动我的 IntellijIDEA 2019.2 - I'm having a hard time launching my IntellijIDEA 2019.2 难以理解枚举“实例化”吗? - Having a hard time understanding enum “instantiation”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM