【Java 基础】引用型数组、Java 继承、super 关键字详解
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                在Java中,数组可以是引用型的,即数组可以作为对象处理。这意味着你可以创建一个数组,并将它作为参数传递给方法或者将它赋值给变量。
public class Main {
    public static void main(String[] args) {
        // 创建一个数组
        int[] myArray = {1, 2, 3, 4, 5};
 
        // 将数组作为参数传递给另一个方法
        printArray(myArray);
 
        // 将数组赋值给另一个变量
        int[] anotherArray = myArray;
        anotherArray[0] = 100; // 这会改变myArray中的第一个元素
 
        // 打印修改后的数组
        printArray(myArray);
    }
 
    public static void printArray(int[] array) {
        for (int i : array) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}在Java中,继承是面向对象编程的一个基本特性。它允许你创建新类,这些新类可以继承一个已经存在的类的属性和方法。
class Parent {
    public void print() {
        System.out.println("Hello from Parent");
    }
}
 
class Child extends Parent {
    // Child类继承了Parent类的print方法
}
 
public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.print(); // 输出 "Hello from Parent"
    }
}super 关键字在Java中用于访问父类的成员。你可以使用 super 来调用父类的构造方法,方法,或者访问父类的成员变量。
class Parent {
    public int x = 100;
 
    public void print() {
        System.out.println("Hello from Parent");
    }
}
 
class Child extends Parent {
    public int x = 200;
 
    public void print() {
        System.out.println("Hello from Child");
    }
 
    public void test() {
        System.out.println(x); // 输出200,因为x是子类的成员变量
        System.out.println(super.x); // 输出100,使用super访问父类的成员变量
 
        print(); // 输出 "Hello from Child",方法被子类覆盖
        super.print(); // 输出 "Hello from Parent",使用super访问父类的方法
    }
}
 
public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.test();
    }
}以上代码展示了如何在Java中使用数组、继承以及super关键字。
评论已关闭