Java基础002

版权声明: https://blog.csdn.net/qq_40905403/article/details/83820949

给类属性赋值的方式

直接在类里面赋值

public class Student {
	String name = "张君瑞";
	int age = 23;
	String sex = "男";
	String address = "阳泉平定";
	void sayHi() {
		System.out.println("我叫" + name + ",我今年" + age + "岁了");
	}
}

这样做,每个对象出来后都长得一模一样

public class Test {
	public static void main(String[] args) {	//程序的主入口
		Student stu = new Student();
		Student stu2 = new Student();
		Student stu3 = new Student();
	}
}

在程序赋值

public class Student{
	String name;
	int age;
	String sex;
	String address;
	void sayHi() {
		System.out.println("我叫" + name + ",我今年" + age + "岁了");
	}
}

这样做太麻烦

public class Test {
	public static void main(String[] args) {	//程序的主入口
		Student s1 = new Student();
		s1.name = "zjr";
		s1.age = 23;
		s1.sex = "男";
		s1.address = "阳泉平定巨城连庄";
		s1.sayHi();
		
		Student s2 = new Student();
		s2.name = "cxl";
		s2.age = 23;
		s2.sex = "女";
		s2.address = "临汾霍州";
		s2.sayHi();
		
		
		Student s3 = new Student();
		s3.name = "ww";
		s3.age = 24;
		s3.sex = "男";
		s3.address = "阳泉平定巨城连庄";
		s3.sayHi();
		
		Student s4 = new Student();
		s4.name = "wsj";
		s4.age = 24;
		s4.sex = "男";
		s4.address = "晋城阳城";
		s4.sayHi();
	}
}

通过构造器赋值(提倡)

public class Student{
	String name;
	int age;
	String sex;
	String address;
	Student(String name,int age,String sex,String address) {	//构造器 this指代当前类对象 
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.address = address;
	}
	void sayHi() {
		System.out.println("我叫" + name + ",我今年" + age + "岁了");
	}
}

这种方式是提倡的,这样做就很不错,代码量少,还很清晰,不容易出错

public class Test {
	public static void main(String[] args) {	//程序的主入口
		Student s1 = new Student("张君瑞",23,"男","平定连庄");
		s1.sayHi();
		
		Student s2 = new Student("成小丽",23,"女","临汾霍州");
		s2.sayHi();

		Student s3 = new Student("王伟",23,"男","平定连庄");
		s3.sayHi();
		
		Student s4 = new Student("王世杰",23,"男","晋城阳城");
		s4.sayHi();
	}
}

重载

解释: 方法名相同,参数列表不同(个数,类型,位置)

public class Aoo{
	void say(){}
	void say(String name){}
	void say(String name,int age){}
	void say(int age, String name){}
	void say(int num){}
}

构造方法是可以重载的,目的是去创造不同的对象,符合更多要求的对象

public class Aoo {
	Aoo() {}			//无参构造 系统默认提供,如果我们提供了构造方法,系统就不提供了,如果还想要无参的,就得自己写
	Aoo(String name, int age) {
		this.name = name;
		this.age = age;
	}
	Aoo(String name) {
		this.name = name;
	}
	Aoo(int age) {
		this("张君瑞",age);	 //通过重载调用参数多的构造,进行属性赋值
	}
}
 

NULL

空: 是针对引用的,如果引用为空,表示不能使用对象了,如果使用对象就会报NullPointerException异常。

public class Aoo {
	String name;
	void sayHi(){}
	public static void main(String[] args) {
		Aoo aoo = new Aoo();
		aoo.name = "zjr";
		aoo.sayHi();
		aoo = null;
		aoo.sayHi();  //报错  因为aoo已经为空了,不在aoo不再指向任何对象
	}
}

== 只用来比较两个基础值是否相等

猜你喜欢

转载自blog.csdn.net/qq_40905403/article/details/83820949