Java基础001

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


这一节,我们解决什么是类,什么是对象,怎样用对象访问类成员的问题

public class Student{
	
}

这就是最简单的java类,我们在大括号中写代码

对象

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

以上我们创建了三个Student类型的对象,分别是stu,stu2,stu3,三个对象是彼此独立的
用一个类,我们可以创造无限个对象,只要内存能装得下
创造出的对象,结构相同,数据不同

类中能写什么?

属性

public class Student{
	String name;
	int age;
	String sex;
	String address;
}

方法

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 stu = new Student();
		stu.name = 'zjr';
		stu.age = 23;
		stu.sayHi();
	}
}

在现实世界中,有猫,老虎,狮子,豹子,这些被我们人类定义为猫科动物,因为他们有共性
在程序中,程序员就是造物主,我们去先定义猫科动物,再去创建各种动物

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();
	}
}

上面这种方式给成员变量(属性)赋值可以赋值,但很麻烦,代码量也很多,而且很容易出错,一不小心就把对象名搞错了,因为长得都一样,肯定要复制,一复制,再去改,有时候有些内容就没改,很容易出错的。

代码的目标: 高内聚,低耦合
也就是代码要精简,耦合度要小

通过实现代码的目标: 这样做,我们修改代码的时候,也就比较方便了。
下一节将体现什么叫高内聚,怎么就方便了。这节不方便的地方在于给属性赋值的时候太麻烦,做的基本都是相同的事儿。

猜你喜欢

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