Cirry's Blog

构造函数

2019-09-24
技术
java
最后更新:2024-06-20
2分钟
367字

构造方法的定义

  • 构造方法名称必须与类名称保持一致。
  • 构造方法不允许设置任何的返回值类型,即:没有返回值定义。
  • 构造方法是在使用关键字new实例化对象的时候自动调用的。
  • 简单类的定义方法
1
class Person{
2
private String name;
3
private int age;
4
public Person(){
5
this("dog",18);
6
}
7
public Person(String name){
8
this(name, 28);
9
}
10
public Person(String name, int age){
11
this.name = name;
12
this.age = age;
13
}
14
15
public void getInfo (){
25 collapsed lines
16
System.out.println("my name is "+this.name+",my age is "+this.age) ;
17
}
18
19
public void setName(String name){
20
this.name = name;
21
}
22
23
public void setAge(int age){
24
this.age = age;
25
}
26
27
public String getName(){
28
return this.name;
29
}
30
public Number getAge(){
31
return this.age;
32
}
33
}
34
35
public class JavaDemo {
36
public static void main( String args []){
37
Person per = new Person("ccc",25);
38
per.getInfo();
39
}
40
}

带静态变量static的类构造

1
class Book{
2
private String name;
3
private int bid ;
4
private double price ;
5
private static int count = 0;
6
public Book(){
7
}
8
public Book(String name , double price){
9
this.bid = count++;
10
this.name = name;
11
this.price = price;
12
}
13
14
public String getInfo(){
15
return "book name:"+this.name+",book price:"+this.price;
13 collapsed lines
16
}
17
public static int getCount (){
18
return count;
19
}
20
}
21
public class JavaDemo {
22
public static void main(String args []){
23
Book b3 = new Book("html", 100.00);
24
Book b2 = new Book("html2", 222200.00);
25
System.out.println(b3.getInfo());
26
System.out.println(Book.getCount());
27
}
28
}

简单类的练习

1
class User{
2
private String name;
3
private int no;
4
5
public User(String name , int no){
6
this.name = name;
7
this.no = no;
8
}
9
10
public void setName(String name ){
11
this.name = name;
12
}
13
14
public void setNo (int no ){
15
this.no = no;
31 collapsed lines
16
}
17
18
public String getName (){
19
return this.name;
20
}
21
22
public int getNo(){
23
return this.no;
24
}
25
26
public String getInfo(){
27
return "my name is "+ this.name+",my no is "+this.no;
28
}
29
}
30
31
public class Demo {
32
public static void main(String args []){
33
User user1 = new User("cirry", 1);
34
User user2 = new User("winnie", 2);
35
System.out.println(user1.getInfo());
36
System.out.println(user2.getInfo());
37
38
user1.setName("cirry666");
39
System.out.println(user1.getNo());
40
System.out.println(user1.getInfo());
41
42
user2.setNo(2);
43
System.out.println(user2.getInfo());
44
45
}
46
}
本文标题:构造函数
文章作者:Cirry
发布时间:2019-09-24
版权声明:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode