Java的:如何将参数传递到构造函数?未定义的方法错误? [英] Java: how to pass arguments into constructor? Undefined method error?

查看:341
本文介绍了Java的:如何将参数传递到构造函数?未定义的方法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我需要一些基本的帮助。下面是我试图从( HTTP学习教程://文档。 oracle.com/javase/tutorial/java/javaOO/classes.html ),但我很困惑,如何实际数据传递到它。问题是我有我的帕斯卡尔的大脑试图学习Java时...

Ok, so I'm in need of some basic help. Here's the tutorial I'm trying to learn from (http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html), but I'm confused as to how to actually pass data into it. The problem is I've got my Pascal brain on when trying to learn java...

下面是我的code。我在做什么错了?

Here's my code. What am I doing wrong?

public class OrigClass{
    public static void main(String[] args){
        StudentData(17, "Jack"); //error here: the method StudentData(int, String) is undefined for the type OrigClass
    }

    public class Student{
        public void StudentData(int age, String name){
            int sAge = age;
            String sName = name;
            System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
        }
    }
}

在此先感谢您的帮助:)

Thanks in advance for the help :)

推荐答案

构造不只是一个方法:你需要给它同名的类,并以运营商,像这样的:

Constructor is not just a method: you need to give it the same name as the class, and call it with a new operator, like this:

public class Student{
    // Declare the fields that you plan to assign in the constructor
    private int sAge;
    private String sName;
    // No return type, same name as the class
    public Student(int age, String name) {
        // Assignments should not re-declare the fields
        sAge = age;
        sName = name;
        System.out.println("Student Name: " + sName + " | Student Age: " + sAge);
    }
}
// This goes in the main()
Student sd = new Student(17, "Jack");

这篇关于Java的:如何将参数传递到构造函数?未定义的方法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆