类与对象的关系
-
类是一种抽象的数据类型,它是对某一类事物的整体描述\定义,但是不能代表一个具体的事物。
-
对象是抽象概念的具体实例。
类的创建
//学生类
public class Student{
String name;
int age;
//方法
public void study(){
System.out.println(this.name + "在学习!");
}
}
//方法类
public class Application{
public static void main(String[] args) {
Student stu = new Student();
stu.name = "小明";
stu.age = 18;
System.out.println(stu.name);
System.out.println(stu.age);
}
}
初始化对象
-
构造器:
-
和类名相同。
-
没有返回值。
-
new关键字 ,本质是在调用构造器。
-
初始化对象。
-
一旦定义了有参构造,无参构造必须显示定义。
-
public class Person{
String name;
public Person(){
}
public Person(Stirng name){
this.name = name;
}
}
//测试
public class Application{
public static void main(String[] args) {
Person per = new Person();
Person per = new Person("小明");
}
}
4701

被折叠的 条评论
为什么被折叠?



