Python 官方文档:入门教程 => 点击学习
目录一、构造方法概述二、构造方法的注意事项三、标准类制作一、构造方法概述 构造方法是一种特殊的方法 作用:创建对象Student stu = new Student(); 格式: p
构造方法是一种特殊的方法
作用:创建对象Student stu = new Student();
格式:
pucli class 类名{
修饰符 类名(参数){
}
}
功能:主要是完成对象数据的初始化
示例代码:
class Student {
private String name;
private int age;
//构造方法
public Student() {
System.out.println("无参构造方法");
}
public void show() {
System.out.println(name + "," + age);
}
}
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s = new Student();
s.show();
}
}
构造方法的创建
如果没有定义构造方法,系统将给一个默认的无参构造方法,如果定义了构造方法,系统将不再提供默认的构造方法
构造方法的重载
如果自定义了无参构造方法,还要使用无参构造方法,就必须再写一个无参数构造方法
推荐的使用方式
无论是否使用,都手工书写无参数构造方法
重要功能
可以使用带参构造,为成员变量进行初始化
示例代码:
class Student {
private String name;
private int age;
public Student() {}
public Student(String name) {
this.name = name;
}
public Student(int age) {
this.age = age;
}
public Student(String name,int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println(name + "," + age);
}
}
public class StudentDemo {
public static void main(String[] args) {
//创建对象
Student s1 = new Student();
s1.show();
//public Student(String name)
Student s2 = new Student("小红");
s2.show();
//public Student(int age)
Student s3 = new Student(30);
s3.show();
//public Student(String name,int age)
Student s4 = new Student("小红",20);
s4.show();
}
}
需求:定义标准学生类,要求分别使用空参和有参构造方法创建对象,空参创建的对象通过setXxx赋值,有参创建的对象直接赋值,并通过show方法展示数据
示例代码:
class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//成员方法
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void show() {
System.out.println(name + "," + age);
}
}
public class StudentDemo {
public static void main(String[] args) {
//无参构造方法创建对象后使用setXxx()赋值
Student s1 = new Student();
s1.setName("小红");
s1.setAge(20);
s1.show();
//使用带参构造方法直接创建带有属性值的对象
Student s2 = new Student("小红",20);
s2.show();
}
}
到此这篇关于Java基础学习之构造方法详解的文章就介绍到这了,更多相关Java构造方法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java基础学习之构造方法详解
本文链接: https://www.lsjlt.com/news/165857.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0