面向对象

2017-03-26  本文已影响0人  chenanle

this和super不能出现在static的方法中

class Bird {
    public void fly() {
        System.out.println("fly in the sky");
    }
}

public class TestOverride extends Bird {
    public void fyl(){
        System.out.println("fly on the ground");
    }
    public static void main(String[] args) {
        TestOverride p = new TestOverride();
        p.fyl();
    }
}
public class TestOverload {
    public String name;
    public String color;
    public int age;

    public TestOverload(){
        System.out.println("无参的构造方法");
    }

    public TestOverload(String name,String color) {
        this.name = name;
        this.color = color;
        System.out.println("有2个参数的构造方法");
    }

    public TestOverload(String name,String color,int age) {
        this(name,color); //这里的this 引用了上一个构造器里的内容,必须放在第一行
        this.age = age;
        System.out.println("有3个参数的构造方法");
    }

    public static void main(String[] agrs) {
        TestOverload p = new TestOverload();
        TestOverload p1 = new TestOverload("chenanle","blue",24);

    }

}
class sub {
    public double size;
    public String name;

    public sub(){}

    public sub(double size,String name) {
        this.size = size;
        this.name = name;
        System.out.println("先打印父类中的语句");
    }
}
public class TestSub extends sub {
    public String color;
    public TestSub(String color,double size,String name) {
        super(size,name);
        this.color = color;
        System.out.println("再打印子类中的语句");
    }
    public static void main(String[] args) {
        TestSub ts = new TestSub("blue",5.6,"chenanle");
        System.out.println("最后打印如下语句");
        System.out.println(ts.size +"--"+ts.color+"--"+ts.name);
    }
}
结果为:
先打印父类中的语句
再打印子类中的语句
最后打印如下语句
5.6--blue--chenanle

多态

class BaseClass{
    public int book = 6;
    public void base() {
        System.out.println("父类普通的方法");
    }
    public void test() {
        System.out.println("父类被重写的方法");
    }
}
class SubClass extends BaseClass {
    public String book = "books";
    public void sub() {
        System.out.println("子类普通的方法");
    }
    public void test() {
        System.out.println("子类重写父类的方法");
    }
}
public class TestDuoTai {
    public static void main(String[] args){
        BaseClass bc = new BaseClass();
        System.out.println(bc.book);
        bc.test();
        bc.base();
        SubClass sc = new SubClass();
        System.out.println(sc.book);
        sc.test();
        sc.base();
        BaseClass polymorphism = new SubClass();   //多态 ,向上转型
        System.out.println(polymorphism.book);
        polymorphism.base();
        polymorphism.test();
    }
}
6
父类被重写的方法
父类普通的方法
books
子类重写父类的方法
父类普通的方法
6
父类普通的方法
子类重写父类的方法
上一篇 下一篇

猜你喜欢

热点阅读