第二章课后习题

练习6

点击查看代码

/*
 * 练习六:
 * 修改前一个程序,让它含有本章所定义的storage()方法的代码段,并调用之
 */

class ttt{
    static int storage(String s){
        return s.length() * 2;
    }
}

public class chapter02test06{

    //编写一个main方法,
    public static void main(String[] args){
        String a = "我是中国人,爱慕拆妮子";//一共占11个字 所以是22个字节
        int i;//用于接收字节数
        i = ttt.storage(a);
        System.out.println(i);
    }
}

这儿因为运用了static定义方法 所以程序没有报错

但是如果 没有加入static 也就是我最开始时候的编写

点击查看代码

/*
 * 练习六:
 * 修改前一个程序,让它含有本章所定义的storage()方法的代码段,并调用之
 */

class ttt{
        int storage(String s){
        return s.length() * 2;
    }
}

public class chapter02test06{

    //编写一个main方法,
    public static void main(String[] args){
        String a = "我是中国人,爱慕拆妮子";//一共占11个字 所以是22个字节
        int i;//用于接收字节数
        i = ttt.storage(a);
        System.out.println(i);
    }
}

那么

想了想 也正常 毕竟在初学Java的时候 

public static void main已是耳濡目染 没有想到定义main方法的时候确实是static静态定义的 

所以javdoc中的报错“无法从静态上下文中引用非静态” 也无可厚非。

 

posted @ 2021-10-15 11:03  哇~龙  阅读(24)  评论(0)    收藏  举报