java 面向对象入门2


在这里插入图片描述

  类中的构造方法,属于类中的特殊方法,主要用于初始化创建对象。如果没有在类中显示定义构造方法,则编译器默认提供无参构造方法。
  特点是名称与类名完全相同;没有返回值类型;创建对象时,触发构造方法的调用,不可通过点语法手动调用。
  构造方法也适用方法重载规则。

public class Student {

	String name;
	int code;
	int age;
	
	
	
	public Student() {
		name = "11";
		code = 9678;
		age = 18;
		
		System.out.println("hhh " + name);
	}
	
	public Student(String cName,int cCode, int cAge) {
		name = cName;
		code = cCode;
		age = cAge;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}

}

public class Test {

	public static void main(String[] args) {
		Student stu1 = new Student();
		System.out.println(stu1.name);
		Student stu2 = new Student("张1",98,15);
		System.out.println(stu2.name);
	}

}

  如已手动添加有参构造方法,则无参构造方法不再默认提供,可根据需求自行添加。

  this关键字。
  this 是类中的默认引用,代表当前实例。当类服务于某个对象时,this则指向这个对象。

public class Student {

	String name;
	int code;
	int age;
	
	public Student() {
		name = "11";
		code = 9678;
		age = 18;
		
		System.out.println("hhh " + name);
	}
	
	public Student(String name,int code, int age) {
		this.name = name;
		this.code = code;
		this.age = age;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}
}

  this 可调用本类中的其他构造方法,只能写在方法内的首行并且只能写一次。

public class Student {

	String name;
	int code;
	int age;
	
	public Student() {
	
	}
	
	public Student(String name) {
		
	}
	
	public Student(String name,int code, int age) {
		this(name);
		this.code = code;
		this.age = age;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值