简体   繁体   English

将数据变量从方法传递给构造器Java

[英]Passing Data Variable from method to Constructor Java

I want to get the value of my variable sub in method and pass it on my Constructor 我想在方法中获取变量sub的值,并将其传递给我的构造方法

// this is my method //这是我的方法

private int sub;
public void getSubj (int sub) {
   this.sub = sub;
}

// and this my constructor //这是我的构造函数

public schedule (int sub) {
    subject = sub;
    System.out.print(subject);
}

Methods call after the constructor finished. 构造函数完成后调用方法。 You cannot call any method of class, before calling its constructor. 在调用类的构造函数之前,不能调用任何类的方法。

You can still call methods inside the constructor. 您仍然可以在构造函数中调用方法。

public schedule (int sub) {
    subject = sub;
    System.out.print(subject);
    getSubj(sub);
}

Your question doesn't make much sense. 您的问题没有多大意义。

When you call a constructor, you are passing it data from outside the instance being created with this constructor. 调用构造函数时,您正在从使用该构造函数创建的实例外部传递数据。

The method getSubj looks like a setter (despite its name). getSubj方法看起来像一个setter(尽管它的名称)。 It is another way to update the state of the object after the constructor is called, but it's not passing anything to the constructor, since it can't be called before the constructor is executed (unless the constructor calls it, in which case the constructor would be passing data to it and not the other way). 这是在调用构造函数之后更新对象状态的另一种方法,但是它没有将任何内容传递给构造函数,因为在执行构造函数之前无法调用该对象(除非构造函数调用它,在这种情况下,构造函数会调用该方法)会将数据传递给它,而不是相反)。

You code would make more sense this way: 这样编写代码将更有意义:

private int sub;
public void setSubj (int sub) // renamed from getSubj, since it's a setter
{
    this.sub = sub;
}

public schedule (int sub) 
{
    this.sub = sub;
}

public static void main (String[] args)
{
    schedule s = new schedule (10); // invoke the constructor
    s.setSubj(20); // invoke the setter method to change the state of the instance
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM