java中的继承代表实例化一个子类,子类依旧可以调用父类的方法和属性,可以省去子类单独编写一些重复代码,例如eat、sleep这种,还有一些通用方法啊,在父类设置后直接子类继承,很方便。多态是指,针对某个类型的方法调用,其真正执行的方法取决于运行时期实际类型的方法。下面是关于继承与多态相关的代码:public class Main { public static void main(String[] args) { Person p = new Student(); System.out.println(p.num); //返回 1 p.run(); //返回 Student.run 不论加不加 override 只要是父类声明的非static方法,子类也有的同名方法,都会调用子类的方法。 System.out.println(p.name); //返回 jack // System.out.println(p.type); // 报错 因为引用了不在引用类型中的变量。 // p
下面的代码中,字符串其实并没有变,变的只是s的指向。// 字符串不可变 public class Main { public static void main(String[] args) { String s = "hello"; System.out.println(s); // 显示 hello s = "world"; System.out.println(s); // 显示 world } }以及这段代码中,输出的是hello,因为从s = "hello" 开辟了hello这个字符串的空间,还有s指向了hello这个字符串;t=s,s是个指针指向的是字符串,所以t也指向hello,那么当s被赋值为world时,s的指针指向了world字符串,并不影响原先的t指针,所以打印t依旧是hello。// 字符串不可变 public class Main { public static void main(String[] args) { St