小白初学Java打卡Day18
类中的方法调用访问修饰符有四种public、protected、默认不写、private一个方法最多只能有一个返回值 如果需要返回多个数据可以用数组。方法里面不能嵌套定义方法。迷糊的点是​ // 类 public class Test { // main方法写在这里类 {} 里面 public static void main(String[] args) { // 程序从这里开始执行 System.out.println(程序启动); } // 其他方法也写在类里面 } ​main是写在类里面的。多个类main 只写其中一个类。public只能拥有一个。传递的是变量的值拷贝 方法内部修改形参不会影响外面的实参。public class Method02 { public class A{//内部类 public void sayOk(){ print(); //同类直接调用,可以写在前面 } public void print(){ System.out.println(hello); } }public static void main(String[] args) { //创建AA对象名字是obj AA obj new AA(); int a 10; int b 20; obj.swap(a, b); System.out.println(maina a b b); //依旧 a10,b20 } } class AA {//外部类与public class Method02同等地位 public void swap(int a, int b) { int tmp a; a b; b tmp; System.out.println(swap内a a b b); }}注意类的位置在代码里了。传参数组传参原始数据会被修改。public class MethodParameter02 { public static void main(String[] args) { B b new B(); int[] arr {1,2,3}; b.test100(arr); System.out.println(arr[0]); //输出200原始数组被修改 } } class B{ public void test100(int[] arr){ arr[0] 200; } }对象传参传递的是对象地址的副本。class Person { int age; public Person(int age) { this.age age; } } public class ParamTest { public static void changeRef(Person p) { // 重点这一行 p new Person(666); } public static void main(String[] args) { Person p1 new Person(10); changeRef(p1); System.out.println(p1.age); // 输出 10不是666 } }// 自定义Person类 class Person { int age; // 构造方法 public Person(int age) { this.age age; } } public class Method03 { // 情况1修改对象内部属性【外部会生效】 public static void modifyProperty(Person p) { p.age 666; } // 情况2让形参指向全新对象【外部不会生效】 public static void changeReference(Person p) { // 仅仅修改副本变量p的指向不影响main里的p1 p new Person(666);//有一个全新的空间是p变成了666原来是和p2一样的地址后来改成另一个地址了 } public static void main(String[] args) { // 测试1修改对象内部属性 Person p1 new Person(10); System.out.println(【测试1调用前】age p1.age); modifyProperty(p1); System.out.println(【测试1调用后】age p1.age); System.out.println(--------------------------------); // 测试2形参重新new对象 Person p2 new Person(10); System.out.println(【测试2调用前】age p2.age); changeReference(p2); System.out.println(【测试2调用后】age p2.age);//10 } }这个有对比更清楚一些Java都是值传递把自己的地址复制一份。最后一个是克隆浅拷贝class Student {//一个类 String name; int age; } class MyTools { //接收旧对象返回一份拷贝的新对象 public Student copyStudent(Student oldStu) { Student newStu new Student(); newStu.name oldStu.name; newStu.age oldStu.age; return newStu; } } public class Method04{ public static void main(String[] args) { Student p new Student(); p.name milan; p.age 100; MyTools tools new MyTools();//类里创建一个对象 Student p2 tools.copyStudent(p); System.out.println(pp.name p.age); System.out.println(p2p2.name p2.age); System.out.println(p p2); // false两个不同对象 } }