day06-面向对象--封装-构造方法&标准的javabean的定义

This commit is contained in:
2025-12-29 09:58:55 +08:00
parent 113268db98
commit 5b1a92991c
3 changed files with 107 additions and 0 deletions

View File

@@ -1,11 +1,68 @@
package com.inmind.object_private03;
/*
Student():就是Student类的默认无参构造方法
普通自定义方法
方法修饰符 返回值类型 方法名(参数列表){
方法体return
}
构造方法
方法修饰符 构造方法名(参数列表){
方法体
}
构造方法:
1.没有返回值类型
2.构造方法名必须跟类名一致
注意:当源文件,进行编译之后编译器扫描整个类的内容,如果它发现你没写构造方法,它会帮你自动添加一个
默认的无参构造方法。如果你写了构造方法,编译器就不会自动添加一个默认的无参构造方法
构造方法是可以重载的。
构造方法的作用通过new调用该构造方法创建对象并且对该对象的属性进行赋值
有参构造方法:创建对象并赋值指定的值
无参构造方法:创建对象并赋值默认初始化值
*/
public class Student {
private String name;
private int age = 20;
private int id;
//默认无参构造方法
public Student(){
}
//满参构造方法
public Student(String name,int age,int id){
this.id = id;
this.name = name;
this.age = age;
}
//有参构造方法
public Student(String name){
this.name = name;
}
public Student(int id){
this.id = id;
}
public Student(String name,int id){
this.id = id;
this.name = name;
}
//学习
public void study(String book) {
System.out.println("学号:"+id+",姓名:"+name+",年龄为"+age+"岁的学生在学"+book);
}

View File

@@ -13,6 +13,7 @@ private权限修饰符最小一个权限被它修饰的内容只能够
*/
public class StudentTest {
public static void main(String[] args) {
//创建一个学生对象
Student s = new Student();
System.out.println(s);
@@ -28,5 +29,9 @@ public class StudentTest {
System.out.println(s.getAge());
System.out.println(s.getId());
System.out.println(s.getName());
//使用满参构造方法创建出学生对象2王五22
Student s1 = new Student("王五", 22, 2);
s1.study("python");
}
}

View File

@@ -0,0 +1,45 @@
package com.inmind.object_private03;
//标准的java类
public class Teacher {
private String name;
private double salary;
private int age;
//alt+inset
//构造方法
public Teacher(String name, double salary, int age) {
this.name = name;
this.salary = salary;
this.age = age;
}
public Teacher() {
}
//get/set
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}