5、函数方法
5.1、方的重载
函数的重载就是在同一个类中允许同时存在一个以上的同名函数,只要它们的参数个数或类型不同即可。在这种情况下,该函数就叫被重载(overloaded)了,这个过程称为函数的重载(method overloading)。
例如:
public class Test{
public static void main(String [] args){
int isum;
double fsum;
isum=add(3,5);
isum=add(3,5,6);
fsum=add(3.2,6.5);
}
public static int add(int x,int y){
reutrn x+y;
}
public static int add(int x,int y,int z){
return x+y+z;
}
public static double add(double x,double y){
return x+y;
}
}
5.2、构造函数
1.构造函数的特点:
具有与类相同的名称;
不含返回值;
不能在方法中用return语句返回一个值
构造方法在程序设计中非常有用,它可以为类的成员变量进行初始化工作,当一个类的实例对象刚产生时,这个类的构造方法就会被自动调用,我们可以在这个方法中加入要完成初始化工作的代码。
注意:在构造方法里不含返回值的概念是不同于“void”的,对于“public void Person()”这样的写法就不再是构造方法,而变成了普通方法,在定义构造方法时不能加了“void”,否则这个方法就不再被自动调用了。
例:
class Person{
public Person(){
System.out.println("the constructor 1 is calling!");
}
private int age = 10;
public void shout(){
System.out.println(“age is ”+age);
}
}
class TestPerson{
public static void main(String[] args){
Person p1=new Person();
p1.shout();
Person p2=new Person();
p2.shout();
Person p3=new Person();
p3.shout();
}
}
结果:
the constructor 1 is calling!
age is 10
the constructor 1 is calling!
age is 10
the constructor 1 is calling!
age is 10
5.3 、构造方法的重载
构造和一般一样也可以重载:
class Person{
private String name=”unknown”;
private int age = -1;
public Person(){
System.out.println(“constructor1 is calling”);
}
public Person(String n){
name = n;
System.out.println("constructor2 is calling");
System.out.println(“name is ”+name);
}
public Person(String n,int a){
name = n;
age = a;
System.out.println(”constructor3 is calling”);
System.out.println(“name and age is ”+name+”;”+age);
}
public void shout(){
System.out.println(“listen to me!!”);
}
}
class TestPerson{
public static void main(String[] args){
Person p1=new Person();
P1.shout();
Person p2=new Person(”Jack”);
P2.shout();
Person p3=new Person(“Tom”,18);
P3.shout();
}
}
运行结果:
constructor1 is calling
listen to me!!
constructor2 is calling
name is Jack
listen to me!!
constructor3 is calling
name and age is Tom;18
listen to me!!
5.4、构造方法的一些细节
1).在Java的每个类里都至少有一个构造方法,如果程序员没有在一个类里定义构造方法,系统会自动为这个类产生一个默认的构造方法,这个默认构造方法没有参数,在其方法体中也没有任何代码,即什么也不做。
2).由于系统提供的默认构造方法往往不能满足编程者的需求,我们可以自己定义类的构造方法,来满足我们的需要,一旦编程者为该类定义了构造方法,系统就不再提供默认的构造方法了。
3).构造方法不能用private修饰。