构造方法
一个对象如果被创建在堆区,那么他的构造方法一定会被执行,构造方法可以用来初始化属性。
为什么要构造
当一个对象内的属性需要被初始化时,可以通过构造方法统一完成。例如下面的代码
package com.yuque.phil616.construction;public class Human {String name;int age;/** a constructor is to initialize the properties.* you can do other things inside, because it just a* methods. nothing different from other methods.* */Human(){name = "Null";age = 0;}/**** @author phil616* @param name name of a human* @param age age of a human*/Human(String name,int age){this.name = name;this.age = age;}}
重载
先来看下方法重载(Overloading)的定义:如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。 具体说明如下:
- 方法名相同
- 方法的参数类型,参数个不一样
- 方法的返回类型可以不相同
- 方法的修饰符可以不相同
- main 方法也可以被重载
以下实例演示了如何重载 MyClass 类的 info 方法:
class MyClass {int height;MyClass() {System.out.println("无参数构造函数");height = 4;}MyClass(int i) {System.out.println("房子高度为 " + i + " 米");height = i;}void info() {System.out.println("房子高度为 " + height + " 米");}void info(String s) {System.out.println(s + ": 房子高度为 " + height + " 米");}}public class MainClass {public static void main(String[] args) {MyClass t = new MyClass(3);t.info();t.info("重载方法");//重载构造函数new MyClass();}}
