zoukankan      html  css  js  c++  java
  • java复用和传参

    java复用和传参的三种方法总结:

      (1) 直接在一个类中调用函数 :

     1 package test1;
     2 
     3 public class a
     4 {
     5     public static void getDate()
     6     {
     7         System.out.println("晨落梦公子");
     8     }
     9     public static void main(String[] agrs)
    10     {
    11         getDate();  
    12     }
    13 }

          这种方法应注意主函数中的调用的的getDate()必须声明为静态(即static)。

      (2)     同包中类中的调用(无参):

     1 package test1;
     2 
     3 public class b 
     4 {
     5     public  int  getDate()
     6     {
     7         int b=1;
     8         return  b;
     9     }
    10 }
     1 package test1;
     2 
     3 public class c
     4 {
     5     public static void main(String[] args) 
     6     {
     7         b b1 = new b(); //使得b1像类b一样使用,即对象,称为对象的引用
     8         int b2 = b1.getDate();
     9         System.out.println(b2);
    10     }
    11 }

        值得一提的是,有了b b1 = new b();,类b中就不用static了(吐槽:多爽,还省了占用内存呢o(* ̄▽ ̄*)o。啥?!你不知道咋省内存的?,下面讲解):

    static意为静态,也就是说程序到执行完后才释放内存。如果用new分配空间,如上例。好处:当b1不用时java编译器会有个垃圾回收站自动释放内存。

        (2)     同包中类中的调用(带参):

     1 package test1;
     2 
     3 public class d 
     4 {
     5     public  int  getDate(int d1)
     6     {
     7         int d = d1;
     8         return d;
     9     }
    10 }
     1 package test1;
     2 
     3 public class e 
     4 {
     5 
     6     public static void main(String[] args)
     7     {
     8         d  da = new d();
     9         int d1 = da.getDate(1);
    10         System.out.println(d1);
    11     }
    12 
    13 }

        参数的作用:可把主函数的同类型数据拿去给调用的函数去处理,得出结果。

    易出错点:1)  如上例int d = d1; 语句容易忽略int;

           2)    上例中 System.out.println(d1);可能写错为System.out.println(da);这时候输出的就是test1.d@16bd8ea,即地址;

    ps:本人小白一名,初识Java,以上也只是自己摸索出的一些门路,估计有不当之处,仅供参考吧。不对,确切的应说,仅供新手参考。

    myGitgub https://github.com/mfx55 希望我的博客能帮到你
  • 相关阅读:
    centos7安装mysql5.7
    Day1:基于ECS搭建FTP服务
    sql多表语句
    SSM多表查询
    ssm中使用逆向工程
    用maven对ssm进行整合
    Maven设置本地仓和阿里云远程仓
    解决maven项目中web.xml is missing and <failOnMissingWebXml> is set to true
    SSM登陆
    理解ConcurrentMap
  • 原文地址:https://www.cnblogs.com/chenluomenggongzi/p/4896331.html
Copyright © 2011-2022 走看看