《6.Java中构造函数》由会员分享,可在线阅读,更多相关《6.Java中构造函数(4页珍藏版)》请在金锄头文库上搜索。
1、构造函数1. 什么是构造函数在 java 中,构造函数是一种用来设置局部变量的值的方法。在 java 中,当对象已经被 创建,编译器会最先调用构造函数。意思是说,所有写入到构造函数的代码都会被执行, 当编译器创建一个对象,当运行时候构造器就自动加载进来。 构造函数/方法,方法的名称和类名一样。public class Car /Class Member Variables int iGear;int iHighestSpeed;String sColor;int iMake;boolean bLeftHandDrive;String sTransmission;int iTyres;int i
2、Doors;/This is the syntax to create a Constructorpublic Car()观察以上代码,Car()这个方法和类名相同,这就是一个构造方法,构造方法不需要返回值。2. 给构造函数传值构造函数是可以传值的,观察以下代码。public class Car /Class Member Variables int iGear;int iHighestSpeed;String sColor;int iMake;boolean bLeftHandDrive;String sTransmission;int iTyres;int iDoors;/Construc
3、tor with values passedpublic Car(String Model, int Make,boolean LeftHandDrive )sModel = Model;iMake = Make;bLeftHandDrive = LeftHandDrive;/Methodpublic void DisplayCharacterstics()System.out.println(“Model of the Car: “ + sModel);System.out.println(“Number of gears in the Car: “ + iGear);System.out.
4、println(“Max speed of the Car: “ + iHighestSpeed);System.out.println(“Color of the Car: “ + sColor);System.out.println(“Make of the Car: “ + iMake);System.out.println(“Transmission of the Car: “ + sTransmission);Main 函数public class ConstructorTestExercise public static void main(String args) /Use th
5、e Car keyword to declare Car Class variable/Passing values to the constructorCar Toyota = new Car(“Camry“,2014,true);Toyota.iDoors = 4;Toyota.iGear = 5;Toyota.iHighestSpeed = 200;Toyota.iTyres = 4;Toyota.sColor = “Black“;Toyota.sTransmission = “Manual“;/Using Car class methodToyota.DisplayCharacters
6、tics();输出结果 Model of the Car: Camry Number of gears in the Car: 5 Max speed of the Car: 200 Color of the Car: Black Make of the Car: 2014 Transmission of the Car: Manual3. 为什么需要构造函数考虑下这么一个场景,把类变量暴露给 Main 方法是不安全的。在这个点上,类成员 变量可以转换私有类型,因为私有类型的变量是不可以其他类访问。在这里,如果定义了 构造函数,在 Main 方法里就不许直接访问类变量。 还是来看 Car Cl
7、ass 代码public class Car /Class Member Variables private int iMake;private int iGear;int iHighestSpeed;String sColor;boolean bLeftHandDrive;String sTransmission;int iTyres;int iDoors;/Default values set in Constructorpublic Car()sModel = “Camry“;iMake = 2014;iGear = 5;public void DisplayCharacterstics
8、()System.out.println(“Model of the Car: “ + sModel);System.out.println(“Number of gears in the Car: “ + iGear);System.out.println(“Max speed of the Car: “ + iHighestSpeed);System.out.println(“Color of the Car: “ + sColor);System.out.println(“Make of the Car: “ + iMake);System.out.println(“Transmissi
9、on of the Car: “ + sTransmission);Main 方法public class ConstructorTestExercise public static void main(String args) /Use the Car keyword to declare Car Class variableCar Toyota = new Car();Toyota.iDoors = 4;Toyota.iHighestSpeed = 200;Toyota.iTyres = 4;Toyota.sColor = “Black“;Toyota.sTransmission = “Manual“;Toyota.bLeftHandDrive = true;/Using Car class methodToyota.DisplayCharacterstics();