类与对象的创建调用
先看一下类与对象的关系,搞清楚概念
创建一个Student类
package com.zsw.oop.demo02;
public class Student {
//属性:字段
String name;//null
int age;//0
//方法
public void study(){
System.out.println(this.name+"在学习");//this代表当前这个类
}
}
创建Application类
调用Student类
package com.zsw.oop.demo02;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
//类:抽象的,实例化
//类实例化后会返回一个自己的对象!student对象就是一个Student类的具体实例!
Student xiaoming = new Student();
Student xh = new Student();
xiaoming.name="小明";
xiaoming.age=3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
System.out.println(xh.name);
System.out.println(xh.age);
}
}
值传递和引用传递
值传递:输出结果都是1
package com.zsw.oop;
//值传递
public class Demo04 {
public static void main(String[] args) {
int a=1;
System.out.println(a);
Demo04.change(a);//值传递,不影响最终结果
System.out.println(a);
}
// 返回值为空
public static void change( int a){
a=10;
}
}
引用传递:输出结果null,zsw
package com.zsw.oop;
//引用传递:对象,本质还是值传递
public class Demo05 {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);
Demo05.change(person);
System.out.println(person.name);
}
public static void change( Person person){
//person 是一个对象:指向的--->Person person = new Person();
//一个具体的人,可以改变属性
person.name="zsw";
}
}
//定义Person类,有一个属性:name
class Person{
String name;
}
仔细体会一下区别。