java - 我很难理解 Java 对象和类

标签 java class object

例子一

/**
 *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;
  }
}

我去了this site我读了它,但我仍然感到困惑。

  1. DataOnly data1 = new DataOnly(); 我知道这一行创建了一个对象。但是有人可以为我打破这条线吗?每个词的作用是什么? DataOnly 是类吗?类型? data1 是变量?我认为 new DataOnly 是对位置的引用。而()是变量所在的位置?我说得对吗?

  2. 他们如何打印data1.LIMITdata1.iMemData1.dMem?他们是否通过查看 DataOnly() 的位置来打印它? DataOnly() 是否引用类 DataOnly

  3. 我完全迷失了 MethodOnly 对象的整个过程。

最佳答案

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?

该行表示创建一个名为“data1”的 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?

DataOnly 只是对象(类)的模板。打印使用从该模板创建的内存中的对象来打印值。

3) I'm just completely lost on the whole process of the MethodOnly object.

对象可以包含数据和执行功能,具体取决于创建它的模板(类)。 MethodOnly 类似乎被定义为仅包含代码而不包含数据。 DataOnly 类似乎被定义为仅存储值而不执行任何操作。

总结
我认为最简单的理解方式是类是对象的蓝图。基于这些蓝图创建对象(使用“new”关键字)并存储在内存中。因此,您所有的工作都将通过对象完成,您只需使用类来告诉它您想要什么类型的对象。

关于java - 我很难理解 Java 对象和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3887126/

相关文章:

java - 如何找到字符串变量中两个数字的总和?

java - setContentView(int) 不起作用

c++ - 那么现在 struct 可以有虚函数并支持继承吗?那么与 classes 有什么区别呢?信息隐藏的真正目的是什么?

javascript - Jquery 将 css 样式应用于除鼠标悬停图像之外的具有特定类的所有元素

java - 了解 JVM 中的对象开销

java - 使用 HashMap 查找字谜

java - Intellij不导入模块的依赖关系

c++ - 结构与对象 C++

javascript - 使用 Fetch API 时出现此错误 : Uncaught (in promise) TypeError: packages. map 不是函数

javascript - 如何从 ng-repeat 内的对象中删除元素?