文章目录
企业里面一般都要构造一个空的构造器,再构造其他的构造器
1:构造器:
类似于类的声明
public Person(){
age=18;
}
1.Person类
Person 类
package com.atguigu.java.day10.exer;
/**
* @author lenovo
* @version 1.0
* @project JavaSE
* @description 1
* @date 2022/10/11 11:27:07
*/
public class Person {
private int age;
private String name;
//构造器
public Person(){
age=18;
}
public Person(String n,int a){
name =n;
age =a;
}
public void setAge(int a) {
if(a<0 || a>130){
// throw new RuntimeException("传入的数据非法");
System.out.println("传入的数据非法");
return ;
}
age=a;
}
public int getAge(){
return age;
}
public void setName(String n){
name=n;
}
public String getname(){
return name;
}
}
PersonTest类
package com.atguigu.java.day10.exer;
/**
* @author lenovo
* @version 1.0
* @project JavaSE
* @description 1
* @date 2022/10/11 11:27:17
*/
public class PersonTest {
public static void main(String[] args) {
Person p1=new Person();
// p.setAge(12);
System.out.println("年龄为:"+p1.getAge());
Person p2=new Person("Tom",21);
System.out.println("name="+p2.getname()+",age="+p2.getAge());
}
}
2:题目:
3.题目二:打印三角形:
4.解决方法:
1.TriAngle:
package com.atguigu.java.day10.exer1;
/**
* @author lenovo
* @version 1.0
* @project JavaSE
* @description
* @date 2022/10/11 16:44:01
*/
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;
}
}
2.TriAngleTest
package com.atguigu.java.day10.exer1;
/**
* @author lenovo
* @version 1.0
* @project JavaSE
* @description 构造器练习:三角形
* @date 2022/10/11 16:40:13
*/\n" +
"public class TriAngleTest {\n" +
" public static void main(String[] args) {\n" +
"\n" +
" TriAngle t1=new TriAngle();\n" +
" t1.setBase(2.0);\n" +
" t1.setHeight(2.4);\n" +
"\n" +
" System.out.println(\"base:\"+t1.getBase()+\",height:"+t1.getHeight());
TriAngle t2=new TriAngle(4.0,10.0);
System.out.println("t2 base:"+t2.getBase()+",t2 height:"+t2.getHeight());
}
}