java编程思想-复用类

/*
一个文件中只能有一个public类
并且此public类必须与文件名相同
*/
class WaterSource
{
    private String s;
    WaterSource()
    {
        System.out.println("WaterSource()");
        s = "constructed";
    }
    //每一个非基本类型的对象都有一个toString()方法,当编译器需要一个String而却只有一个对象时,该方法便会被调用
    public String toString()
    {
        return s;
    }
}

public class first
{
    private WaterSource source = new WaterSource();
    public String toString()
    {
        return "source = " + source;
    }
    public static void main(String[] args)
    {
        first fir = new first();
        System.out.println(fir);
    }
}
/*
WaterSource()
source = constructed
*/
//继承语法,java用super关键字表示超类,当前类从超类继承来
//一个程序中含有多个类,只有命令行所调用的那个类的main()方法会被调用
class Cleanser
{
    private String s = "Cleanser";
    public void append(String a)
    {
        s += a;
    }
    public void apply()
    {
        append(" apply()");
    }
    public String toString()
    {
        return s;
    }
    public static void main(String[] args)
    {
        Cleanser x = new Cleanser();
        System.out.println(x);
    }
}

public class first extends Cleanser
{
    public void apply()
    {
        append(" first.apply()");
        super.apply();
    }
    public static void main(String[] args)
    {
        first x = new first();
        x.apply();
        System.out.println(x);
    }
}
//java会自动在派生类的构造器中插入对基类构造器的调用
class Art
{
    Art()
    {
        System.out.println("Art constructed");
    }
}

public class first extends Art
{
    public first()
    {
        System.out.println("first constructed");
    }
    public static void main(String[] args)
    {
        first x = new first();
    }
}
/*
Art constructed
first constructed
*/
//如果没有默认的基类构造器,或者想调用一个带参数的基类构造器,就必须用super显式调用基类构造器,且必须是在构造器的起始处就要这么做,否则编译器会
//报错,因为没有默认的基类构造器
class Game
{
    Game(int i)
    {
        System.out.println("Game" + i);
    }
}
public class first extends Game
{
    first()
    {
        super(11);
        System.out.println("first");
    }
    public static void main(String[] args)
    {
        first x = new first();
    }
}
/*
Game11
first
*/

 

posted @ 2015-10-14 16:25  合唱团abc  阅读(289)  评论(0编辑  收藏  举报