一、方法的重载
在Java中,通过定义不同的参数列表来实现方法的重载
public class Point {
private int x,y;
Point (int x){
this(x,x);
}
Point (int x,int y){
this.x = x;
this.y = y;
}
public double distance(){//计算点到原点的距离
return Math.sqrt(Math.pow(this.x, 2)+Math.pow(this.y, 2));
}
public double distance(int x,int y){//计算两点之间的距离
return Math.sqrt(Math.pow(this.x-x, 2)+Math.pow(this.y-y, 2));
}
public static void main(String [] args){
Point p1 = new Point(10,27);
System.out.println(p1.distance());
System.out.println(p1.distance(4,11));
}
}
区分重载方法的是参数列表,所以重载的函数在方法名上可以相同,返回值类型可以相同可以不同,但是参数列表必须不同。参数列表的不同,可以是参数类型不同,也可以是参数个数不同。
二、类的继承
类的继承可以简化类的定义,提高代码的复用率。Java只支持单继承,即一个子类只能有一个父类。但是一个父类可以有多个子类。
子类不会继承父类的私有成员和构造方法。子类要调用父类的构造方法,必须在子类构造方法的第一行使用super()方法调用父类的构造方法。
继承使用关键字extend,语法为“class 子类类名 extend 父类类名{}”
public class Father {
private String name;
Father(){
this.name="穆勒";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Son extends Father {
Son(){
System.out.println(getName());
}
public static void main(String [] args){
Son s1 = new Son();
}
}
static关键字用于定义静态的成员,静态的成员可以直接被类名调用,并被所有的成员共享。
因为静态成员优于对象存在,所以在静态的方法中,不能调用this和super方法。
在静态的方法中,只能调用静态的属性
静态的成员,在类加载的时候初始化,静态变量的值在各个对象中通用。
下面的类中,count是静态变量,用于统计对象创建的次数。
public class Statics {
private static int count = 0;
public Statics(){
count++;
}
public static int getCount() {
return count;
}
public static void setCount(int count) {
Statics.count = count;
}
public static void main(String[]args){
new Statics();
new Statics();
new Statics();
new Statics();
new Statics();
Statics s1 = new Statics();
System.out.println(s1.getCount());
}
}