一、基础
Demo1.java:
public class Demo1 {
public static void main(String[] args) {
// Student.say();
// 对象类型 对象名字 = 对象值
Student student = new Student();
student.say();
}
}
Student.java:
public class Student {
// public static void main(String[] args) {
// System.out.println("student");
// }
// 非静态方法
public void say() {
System.out.println("student");
}
}
二、调用
public class Demo2 {
public static void main(String[] args) {
int a = 1;
System.out.println(a); // 1
Demo2.change(a);
System.out.println(a); // 1
// ----------------分割线----------------
Person person = new Person();
System.out.println(person.name); // null
Demo2.changeP(person);
System.out.println(person.name); // 赵四
}
public static void change(int a){
a = 10;
}
// ----------------分割线----------------
public static void changeP(Person person){
// person是一个对象:指向=>Person person = new Person();
person.name = "赵四";
}
}
class Person{
String name;
}
三、规范化
Application.java:
‘一个项目应该只有一个main方法’
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
// 实例化 学生类
Student student = new Student();
student.name = "赋值咯~";
System.out.println(student.name);
}
}
Student.java:
//学生类
public class Student {
// 属性:字段
String name;
int age;
// 方法
public void study() {
System.out.println(this.name);
}
}
四、构造器
Application.java:
//一个项目应该只有一个main方法
public class Application {
public static void main(String[] args) {
// 没有传参走public Person() {}
Person xiaomi = new Person();
// 有传参走public Person() {(String name) {this.name = name;}
Person xiaohong = new Person("xiaohong");
System.out.println(xiaomi.name);
System.out.println(xiaohong.name);
}
}
Application.java:
public class Person {
String name;
// alt+insert快速生成↓
public Person() {
}
public Person(String name) {
this.name = name;
}
}