栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 构造器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 构造器

概念


案例1

package lesson.l11_oop2;


public class Person {
    private int age;
    private String name;

    public Person() {
        this.age = 18;
    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public void setAge(int age) {

        if (age >= 0 && age <= 130) {
            this.age = age;
        } else {
//            this.age = 0;
            throw new RuntimeException("传入的数据非法");
        }
    }

    public int getAge() {
        return this.age;
    }
}

class PersonTest {
    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(9);
        System.out.println(person.getAge());

        Person person1 = new Person();
        System.out.println(person1.getAge());

        Person person2 = new Person(30, "dq");
        System.out.println(person2.getAge());
    }
}
案例2


海伦公式:
已知三角形三边a,b,c,则:
p=(a+b+c)/2
S=sqrt[p(p-a)(p-b)(p-c)]

package lesson.l11_oop2;


public class TriAngle {
    private Double base;
    private Double height;

    public TriAngle() {

    }

    public TriAngle(Double base, Double height) {
        this.base = base;
        this.height = height;
    }

    public Double getBase() {
        return this.base;
    }

    public Double getHeight() {
        return this.height;
    }

    public Double getArea() {
        return (this.base*this.height)/2;
    }
}

属性赋值的先后顺序

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003771.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号