Home  >  Q&A  >  body text

Java中,构造方法,创建两个对象的时候,找不到符号了。。自学,求解。。

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;
    }
}
天蓬老师天蓬老师2743 days ago472

reply all(6)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:56:30

    I didn’t write a default constructor

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:56:30

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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:56:30

    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().

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:56:30

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:56:30

    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().

    reply
    0
  • PHPz

    PHPz2017-04-18 10:56:30

    Additional note: Do not use Pinyin

    reply
    0
  • Cancelreply