一个类即使什么都不写也会默认存在一个方法(构造器)
类中的构造器也称为构造方法,是在进行创建对象的时候必须要调用的。构造器有以下两个特点:
- 必须和类的名字相同
- 必须没有返回类型,也不能写void
package com.xzc.oop; public class Constructor { public Constructor(){//构造器 } }
构造器核心的作用:(IDEA中快捷键alt+insert)
- 使用new关键字,必须要有构造器(本质是在调用构造器)
- 用来初始化值
package com.xzc.oop; public class Student{ String name; public Student(){ this.name = "xzc";//this.()意思是()作为该类的类变量并将其取出进行一系列 *** 作 } public Student(String name){ this.name = name;//this.name对应类变量,name对应传入的实参。 } }
package com.xzc.oop; import com.xzc.oop.Student; public class Application { public static void main(String[] args) { Student student = new Student(); System.out.println(student.name);//xzc Student student1 = new Student("zyj"); System.out.println(student1.name);//zyj } }
最后实现一个给变量互换值的实例:
package com.xzc.oop; public class Change { int a = 10; int b = 20; public static void main(String[] args) { Change change = new Change(); System.out.println(change.a + ", " + change.b);//10, 20 change.ex(change.a, change.b); System.out.println(change.a + ", " + change.b);//20, 10 }//change.a和change.b为对应的数值而不是变量 public void ex(int a, int b){ this.a = b; this.b = a; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)