java 构造器

Posted DQ_CODING

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 构造器相关的知识,希望对你有一定的参考价值。

概念


案例1

package lesson.l11_oop2;

/**
 * Illustration
 *
 * @author DengQing
 * @version 1.0
 * @datetime 2022/7/3 15:28
 * @function
 */
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)
            throw new RuntimeException("传入的数据非法");
        
        this.age=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;

/**
 * Illustration
 *
 * @author DengQing
 * @version 1.0
 * @datetime 2022/7/3 16:22
 * @function
 */
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;
    


属性赋值的先后顺序

以上是关于java 构造器的主要内容,如果未能解决你的问题,请参考以下文章

java构造方法和方法的区别

Java的构造器

Java的构造器

Java面向对象之构造器

Java构造器的理解

Java基础篇---11.构造器