Java中,构造方法,创建两个对象的时候,找不到符号了。。自学,求解。。
天蓬老师
天蓬老师 2017-04-18 10:54:30
0
6
465
public class Lan{
    public static void main(String []agrs){
        /*
        Person p1=new Person();
        p1.age=8;
        p1.Test();
        System.out.println("第一个为"+p1.age);
        创建这一个的时候就不行,提示找不到符号,在“Person p1=new Person()”的new这里提示的,去掉可就没问题。。
        */
        Person p2=new Person(7,"小五");
        p2.Test();
        p2.jisuan();
        System.out.println("第二个为"+p2.age);
    }
}
class Person{
    int age;
    String name;
    public void jisuan()
    {
        int i=2;
        System.out.println(i);
    }
    public void Test(){
        System.out.println("做测试1");
    }
    Person(int age,String name){
        this.age=age;
        this.name=name;
    }
}
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(6)
刘奇

I didn’t write a default constructor

刘奇

To reply to the question above, when did Java become private without writing access modifiers? Am I using fake java?

洪涛

When you show the written constructor. A default constructor will not be generated.
Just add Person(){

  
}

Note
When you override the constructor of a class, you must override the empty constructor.
Because some frameworks will look for this default constructor when creating objects through reflection.

Also, please change the Test() method to test().

洪涛

The parameterized constructor of the Person class overrides the default constructor.
Note: The default constructor has no parameters
So if you use it like this: Person p1=new Person();
You need to specify a parameterless constructor in the Person class. Or just remove the constructor with parameters.

Peter_Zhu

Because you defined the constructor in the Person class, the default constructor Person() will not be created, but your custom constructor will be used.
You can also use function overloading and write a constructor Person().

PHPzhong

Additional note: Do not use Pinyin

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!