10 多态 | 数组内容比较 | 单态模式

来源:互联网 发布:网络军事评论员 编辑:程序博客网 时间:2024/05/18 00:34

1,关于多态:父类或者接口类型的引用指向子类或者实现该接口的类的对象。

public class Test {public static void main(String[] args) {A a = new B();a.test();}}class A{public void test(){System.out.println("A");}}class B extends A{public void test(){System.out.println("B");}}
接口

public class Test {public static void main(String[] args) {C c=new D();c.test();}}interface C{public void test();}class D implements C{@Overridepublic void test() {System.out.println("D");}}



多态是编译时的行为?还是运行时的行为?或者说多态既可以是编译时的行为也可以是运行时的行为。

2,多态就是运行时的行为。方法的重写是多态,方法的重载不是多态。

package com.test;import java.util.Random;public class Test {public A get() {Random r = new Random();int i = r.nextInt(3);switch (i) {case 0:return new B();case 1:return new C();case 2:return new D();}return null;}public static void main(String[] args) {A a = new Test().get();a.test();}}class A{public void test(){System.out.println("A");}}class B extends A{public void test(){System.out.println("B");}}class C extends A{public void test(){System.out.println("C");}}class D extends A{public void test(){System.out.println("D");}}
运行时 才知道具体是那个对象。

3,数组的比较

char[] ch1 = new char[2];ch1[0] = 'a';ch1[1] = 'b';char[] ch2 = new char[2];ch2[0] = 'a';ch2[1] = 'b';System.out.println(ch1.equals(ch2));

输出false

char[] ch1 = new char[2];ch1[0] = 'a';ch1[1] = 'b';char[] ch2 = new char[2];ch2[0] = 'a';ch2[1] = 'b';String s1 = new String(ch1);String s2 = new String(ch2);System.out.println(s1.equals(s2));
输出true

char[] ch1 = new char[2];ch1[0] = 'a';ch1[1] = 'b';char[] ch2 = new char[2];ch2[0] = 'a';ch2[1] = 'b';System.out.println(Arrays.equals(ch1, ch2));

输出true

4,单态模式,特性 构造函数必须为private,返回方法必须为static

public class Test {private static Test test = new Test();private Test(){}public static Test getSingle(){return test;}}
第一种写法

public class Test {private static Test test;private Test(){}public static Test getSingle(){if(test == null){test = new Test();}return test;}}







0 0
原创粉丝点击