值传递和引用传递
package com.ljh.oop;
//值传递
public class Demo1 {
public static void main(String[] args) {
int a =1;
System.out.println(a);
Demo1.change(a);
System.out.println(a);
}
public static void change(int a){
a = 10;
}
}
引用传递
package com.ljh.oop;
//引用传递:对象,本质还是值传递
public class Demo2 {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name);//null
change(person);
System.out.println(person.name);//ljh
}
public static void change(Person person){
person.name = "ljh";
}
}
//定义一个Person类,有一个属性
class Person{
String name;//null
}
类与对象的关系
package com.ljh.oop.Demo2;
//学生类
public class Student {
//属性:字段
String name;//null
int age;//0
//方法
public void study(){
System.out.println(this.name+"学习");
}
}
package com.ljh.oop.Demo2;
//一个项目应该只存一个main方法
public class Application {
public static void main(String[] args) {
//类:抽象的,实例化
//类实例化会返回一个自己的对象
//student对象就是Student类的具体实例
Student xiaoming = new Student();
Student xiaohong = new Student();
xiaoming.name = "小明";
xiaoming.age = 3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
}
}
创建和构造
Person类
package com.ljh.oop.Demo2;
//java-->class
public class Person {
//一个类即使什么都不写,它也会存在一个方法
//显示的定义构造器
String name;
//实例化初始值
//1.使用new关键字,必须要有构造器
public Person(){
this.name = "ljh";
}
//有参构造,一旦定义了有参构造,无参就必须现实定义
public Person(String name) {
this.name = name;
}
//alt+insert
}
Student类
package com.ljh.oop.Demo2;
//学生类
public class Student {
//属性:字段
String name;//null
int age;//0
//方法
public void study(){
System.out.println(this.name+"学习");
}
}
运行调用
package com.ljh.oop.Demo2;
//一个项目应该只存一个main方法
public class Application {
public static void main(String[] args) {
//类:抽象的,实例化
//类实例化会返回一个自己的对象
//student对象就是Student类的具体实例
Student xiaoming = new Student();
Student xiaohong = new Student();
xiaoming.name = "小明";
xiaoming.age = 3;
System.out.println(xiaoming.name);
System.out.println(xiaoming.age);
Person person = new Person();
System.out.println(person.name);
Person person1 = new Person("kkdsla");
System.out.println(person1.name);
}
}
创建对象内存分析
package com.ljh.oop.Demo3;
public class Pet {
public String name;
public int age;
//无参构造
public void shout(){
System.out.println("叫了一声");
}
}
package com.ljh.oop.Demo3;
public class Application {
public static void main(String[] args) {
Pet dog = new Pet();
dog.name = "旺财";
dog.age = 3;
dog.shout();
System.out.println(dog.name);
System.out.println(dog.age);
Pet cat = new Pet();
}
}