Java学习笔记(16)——构造方法、this、方法重载

这里将自己学习java及其应用的一些笔记、积累分享一下,如果涉及到了文章、文字侵权,请联系我删除或调整。


一、构造方法

1.1 概述

  • 构造方法是新建对象时执行的一个特殊方法

new Soldier()

new AK47()

new Score()

  • 构造一个对象之后,立即执行的一个方法
  • 一个类,必须有构造方法
  • 如果自己不定义,编译器会添加默认构造方法

class A {

     public A() {

     }

}

  • 构造方法重载

多个不同参数的构造方法

class A {

    public A() {}

    public A(int a) {}

    public A(int a, double d) {}

    public A(String s, int a) {}

    public A(String s) {}

}

1.2 练习:学生类

项目:学生
类:Test1, Student

package day0702;

public class Student {
	int id;
	String name;
	String gender;
	int age;

    // 注意重载构造函数之间的调用关系
	public Student() {
	}
	public Student(int id,String name) {
		this(id, name, null);
	}
	public Student(int id,String name,String gender) {
		//重载的构造方法之间调用
		this(id,name,gender,0);
	}
	public Student(int id,String name,String gender,int age) {
		this.id = id;
		this.name = name;
		this.gender = gender;
		this.age = age;
	}

	public String toString() {
		return id+", "+name+", "+gender+", "+age;
	} 
}
package day0702;

public class Test1 {
	public static void main(String[] args) {
		Student s1 = new Student();
		Student s2 = new Student(1,"张三");
		Student s3 = new Student(1,"张三","男");
		Student s4 = new Student(1,"张三","男",22); 
		System.out.println(s1.toString());
		System.out.println(s2.toString());
		System.out.println(s3.toString());
		System.out.println(s4.toString());
	} 
}

二、this

2.1 概述

  • 两种用法:

this.xxx

this(...)

2.1 this.xxx用法

  • this 特殊引用,引用当前对象的地址
  • this.xxx 调用成员变量或函数
  • 当有重名局部变量,必须用this.xx调用成员变量

​​​​​​​​​​​​​​2.2 this(…)用法

  • 构造方法之间调用
  • 目的是减少代码重复,方便维护修改
  • 一般从参数少的方法,调用参数多的方法
  • this(...) 必须是首行代码

​​​​​​​​​​​​​​​​​​​​​三、Overload方法重载

3.1 概述

  • 同名不同参的方法

void f() {}

void f(int i) {}

int f(double d) {}

static void f(String s) {}

 

println()

println(int)

println(double)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值