首页 > 编程语言 > 详细

java编程思想-复用类

时间:2015-10-14 17:49:10      阅读:260      评论:0      收藏:0      [点我收藏+]
/*
一个文件中只能有一个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
*/

 

java编程思想-复用类

原文:http://www.cnblogs.com/ljygoodgoodstudydaydayup/p/4877829.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!