20. java面向对象 - 构造器
一、定义
构造器作用就是创建对象,或创建对象的同时为对象进行属性初始化,创建多个构造器以此构成重载。如果没有显示定义类的构造器的话,则系统默认提供一个空参构造器。new Person()。一旦我们显示定义了构造器,系统就不提供了默认构造器。
构造器定义格式:修饰符 类名(形参列表)
1. 无参数
public class Person {
String name;
int age;
public Person(){
System.out.println("person()...");
}
}
class PersonTest{
public static void main(String[] args) {
Person per = new Person();
//person()...
}
}
2. 有参数
public class Person {
String name;
int age;
public Person(String n){
name = n;
System.out.println("person_name is " + name);
}
}
class PersonTest{
public static void main(String[] args) {
Person per = new Person("tom");
//person_name is tom
}
}
二、实例
编写两个类,TriangleTest和Triangle。其中Triangle类中声明私有的底边和高,同时声明公共方法去访问。此外提供必要的构造器,测试类求三角形面积。
Triangle
public class Triangle {
private double base;
private double height;
//构造方法
public Triangle() {
}
public Triangle(double b, double h) {
base = b;
height = h;
}
//私有属性公有化
public void setBase(double b) {
base = b;
}
public double getBase() {
return base;
}
public void setHeight(double h) {
height = h;
}
public double getHeight() {
return height;
}
public double area(double b, double h) {
return b * h / 2;
}
}
TriangleTest
public class TriangleTest {
public static void main(String[] args) {
Triangle angle = new Triangle();
double base = angle.getBase();
double height = angle.getHeight();
System.out.println("base is " + base + ", " + "height is " + height);
Triangle angleTwo = new Triangle(10, 20);
angleTwo.setHeight(100);
// 500.0
System.out.println("面积是" + angleTwo.area(angleTwo.getBase(), angleTwo.getHeight()));
}
}