java构造函数传递自身,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...

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");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值