对象中在方法中使用的参数

huangapple go评论65阅读模式
英文:

Object used parameter in a method

问题

我是Java的新手,所以如果这听起来像个愚蠢的问题,请原谅我。
有人能解释一下这个方法中发生了什么吗?

public static void policyInNoFaultState( AutoPolicy policy ) <===line in question

“policy”是来自AutoPolicy的对象类型吗?因此policy会继承AutoPolicy的所有内容吗?
这是我可以使用“点”命令的原因,例如policy.getAccountNumber(),policy.getMakeAndModel()

我贴出了我认为与这个问题有关的程序部分。

我感谢您能提供的任何帮助。

//创建AutoPolicy对象
AutoPolicy policy1 = new AutoPolicy(11111111,“Toyota Camary”, “NJ”);
AutoPolicy policy2 = new AutoPolicy(22222222, “Ford Fusion”, “ME”);

//创建policyInNoFaultState方法以显示结果
  public static void policyInNoFaultState( AutoPolicy policy ){

            System.out.println(“汽车保单:”);
            System.out.printf(“帐户号码: %d;汽车: %s;%n州份 %s %s 无过失状态%n%n”,
            policy.getAccountNumber(), policy.getMakeAndModel(),policy.getState(),(policy.isNoFaultState() ? “是”: “不是”));

}//policyInNoFaultState的结尾
英文:

I'm a Java newbie so excuse me if this sounds like a dumb question.
Can someone explain to me what is going on with this method?

public static void policyInNoFaultState( AutoPolicy policy ) <===line in question

Is "policy" of object type from AutoPolicy? therefore policy inherits everything AoutoPolicy has?
Is this the reason I can use the "Dot" command exp. policy.getAccountNumber(), policy.getMakeAndModel()

I pasted part of the program I think applies to this question.

I appreciate any help you can give.

//Creating AutoPolicy ojbects
AutoPolicy policy1 = new AutoPolicy(11111111,"Toyota Camary", "NJ");
AutoPolicy policy2 = new AutoPolicy(22222222, "Ford Fusion", "ME");

//Creating policyInNoFaultState method to display results
  public static void policyInNoFaultState( AutoPolicy policy ){

            System.out.println("The auto policy:");
            System.out.printf("Account #: %d; Car: %s;%nState %s %s a no-fault state%n%n",
            policy.getAccountNumber(), policy.getMakeAndModel(),policy.getState(),(policy.isNoFaultState() ? "is": "is not"));

}//End of policyInNoFaultState

答案1

得分: 1

Java中的类定义了一种类型,基本上充当了从该类创建的所有实例(对象)的模板。这个模板定义了该类型的所有实例可用的数据(字段)和行为(方法)。类型的“静态”成员在所有实例之间共享,而非静态成员(也称为“实例成员”)在实例之间是不同的。

考虑以下简单的示例(注意,这不保证关于如何定义和使用类和实例的最佳实践):

class MyType {
  public static int Shared = 42;
  public int NonShared;

  public void Print() {
    System.out.println("This is me: " + (Shared + NonShared));
  }
}

您可以创建该类的多个实例,它们将共享相同的共享字段,但每个实例的实例字段具有各自的值:

MyType a = new MyType();
MyType b = new MyType();

a.NonShared = 21;
b.NonShared = 84;

a.Print(); // 输出 "This is me: 63"
b.Print(); // 输出 "This is me: 126"

a.Shared = 0;

a.Print(); // 现在输出 "This is me: 21"
b.Print(); // 现在输出 "This is me: 84"

ab 是类/类型 MyType 的实例。在某种程度上,422184 都是类型 int 的实例。

当您定义一个方法来操作值时,必须指定方法应该能够处理哪种类型的值。这是通过为每个参数指定类型来完成的。让我们看另一个任意的示例方法:

static String format(MyType object, String info) {
  return info + ".NonShared = " + object.NonShared;
}

上面的方法返回一个类型为 String 的单个实例,它的参数分别是类型为 MyTypeString 的两个参数。这是必需的,以便编译器知道每个参数可用的成员(字段或方法)。否则,调用 object.NonShared 就不可能实现。

MyType c = new MyType();
c.NonShared = 7;
String formatted = format(c, "formatting");
System.out.println(formatted); // 输出 "formatting.NonShared = 7"

请注意,在这种简单情况下,变量 c 的类型与参数 object 的类型完全匹配。这不是必需的,您可以将任何子类型(或“子类”)传递给参数。参数的类型仅定义了传递给函数的任何参数必须支持的最小成员数量。您可以将其视为输入参数和处理函数之间的合同。

static Integer firstValue(Collection<Integer> list) {
  list.get(0);
}

List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);

firstValue(numbers);

上面的代码将无法工作。它甚至不会编译通过!尽管 numbers 是接口类型 List 的一个实例,具体的实现类型是 ArrayList,并且具有一个实例方法 get,但该方法在方法内部不可用(也不可知)。方法只能使用 Collection 类型。尽管其实现(子类型、子类)可能会提供它,但 Collection 类型并未定义 get 方法。

通过为任何给定任务使用最小可能的类型,您可以获得很大的灵活性。所有集合都实现了 add 方法。通过定义一个可以使用 Collection 的方法,您可以传递任何遵循该类型的实现并对其进行修改:

static void addValue(Collection<Integer> bag) {
  bag.add(4);
}

List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Deque<Integer> stack = new ArrayDeque<>();
Queue<Integer> queue = new PriorityQueue<>();

addValue(list);
addValue(set);
addValue(stack);
addValue(queue);

希望这能解答您的疑问!如果有任何仍不清楚的细节,请在评论中指出,我将努力扩展我的回答以涵盖更多内容。

英文:

A class in Java defines a type and basically acts as template for all instances (objects) created from that class. This template defines data (fields) and behavior (methods) available for all of instances of this type. "Static" members of the type are shared between all instances and non-static members (also called "instance members") are distinct between instances.

Consider the following simple example (beware, this makes no promises about best practices how to define and use classes and instances):

class MyType {
  public static int Shared = 42;
  public int NonShared;

  public void Print() {
    System.out.println(&quot;This is me: &quot; + (Shared + NonShared));
  }
}

You can create several instances of this class which will all share the same shared field but each have their own value for the instance field:

MyType a = new MyType();
MyType b = new MyType();

a.NonShared = 21;
b.NonShared = 84;

a.Print(); // prints &quot;This is me: 63&quot;
b.Print(); // prints &quot;This is me: 126&quot;

a.Shared = 0;

a.Print(); // now prints &quot;This is me: 21&quot;
b.Print(); // now prints &quot;This is me: 84&quot;

a and b are instances of class/type MyType. In a way, 42, 21, and 84 are instances of the type int.

When you define a method to act on values, you have to specify which kind of values the method should be able to handle. This is done by specifying the type for each of its parameters. Let's have a look at another arbitrary example method:

static String format(MyType object, String info) {
  return info + &quot;.NonShared = &quot; + object.NonShared;
}

Above method returns a single instance of type String and works one two parameters of type MyType and String respectively. This is required so that the compiler knows which members (fields or methods) are available for each parameter. Otherwise calling object.NonShared would not be possible.

MyType c = new MyType();
c.NonShared = 7;
String formatted = format(c, &quot;formatting&quot;);
System.out.println(formatted); // prints &quot;formatting.NonShared = 7&quot;

Note that in this simple case, the type of variable c matches the type of the parameter object exactly. This is not required, you can pass any subtype (or "child class") to the parameter. The parameter's type merely defines the minimum number of members that must be supported by any argument that is passed to the function. You can think of it as a contract between the input parameter and the processing function.

static Integer firstValue(Collection&lt;Integer&gt; list) {
  list.get(0);
}

List&lt;Integers&gt; numbers = new ArrayList&lt;&gt;();
numbers.add(1);
numbers.add(2);

firstValue(numbers);

The above code will not work. It will not even compile! Even though numbers is an instance of the interface type List with concrete implementation type ArrayList and has an instance-method get, this is not available (nor known) inside the method, which can only work with Collection types. The Collection type does not define an get method, despite implementations of it (sub types, child classes) might provide it.

By using the smallest possible type for any given task, you gain a lot of flexibility. All collections implement the add method. By defining a method which can work with Collection, you can pass in any implementation which adheres to this type and modify it:

static void addValue(Collection&lt;Integer&gt; bag) {
  bag.add(4);
}

List&lt;Integer&gt; list = new ArrayList&lt;&gt;();
Set&lt;Integer&gt; set = new HashSet&lt;&gt;();
Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();
Queue&lt;Integer&gt; queue = new PriorityQueue&lt;&gt;();

addValue(list);
addValue(set);
addValue(stack);
addValue(queue);

I hope this clears things up! If there is any detail that is still unclear, please point it out in the comments and I will try to extend my answer with further points.

答案2

得分: 0

在这里,“policy”持有一个“AutoPolicy”类型的对象的引用编号。它指向在参数中传递的对象。

为了更好地理解,您可以阅读关于“Java中按值传递和按引用传递”的主题。

英文:

Here "policy" is holding the reference number of an object of "AutoPolicy" type. That is pointing the object passed in parameter.

For better understanding you can go through topic "pass by value and pass by reference in java"

huangapple
  • 本文由 发表于 2020年8月16日 04:03:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63430338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定