zoukankan      html  css  js  c++  java
  • 暑假自学(12)方法的值传递机制

    方法的值传递机制:
    如果参数是基本数据类型,此时实参赋给形参的是实参真实存储的数据值。
    如果参数是引用数据类型,此时实参赋给形参的是实参存储数据的地址值。
    令两个基本数据类型的变量交换值的方法:
    1.新定义一个类,并在类中写明类型相同的数据成员
    2.在主函数外(不是在类内)定义一个函数用于交换,形参为新类
    3.调用函数,并输出类内的数据成员。
    注意:1.目前在类中调用方法只能通过类来调用,所以调用主函数外定义的函数时,需要以主函数的类命名一个对象来调用。(若在主函数下定义两个类之间进行调用则直接调用)
    2.输出时要输出类内成员函数,才能实现交换,数据本身没有实现交换。
    代码样例:
    public class text3 {
    public static void main(String[] args) {
    int a,b;
    a = 10;
    b = 20;
    System.out.println(a+" "+b);
    text3 jojo = new text3();
    //直接定义函数调用*************
    // jojo.swap(a, b);//失败
    // System.out.println(a+" "+b);
    //*****************************
    Swapc tem = new Swapc();
    tem.a = a;
    tem.b = b;
    jojo.swap(tem);
    System.out.println(tem.a+" "+tem.b);//成功
    }
    //**********************************
    // public void swap(int a,int b)
    // {
    // int temp;
    // temp = a;
    // a = b;
    // b = temp;
    // }
    //**********************************
    public void swap(Swapc at)
    {
    int temp;
    temp = at.a;
    at.a = at.b;
    at.b = temp;
    }
    }
    class Swapc{
    int a;
    int b;

    }

    此外梳理了值传递内存分配:

    public class memtext {
    public static void main(String[] args) {
    memtext test = new memtext();

    }
    public void first() {
    int i = 5;
    Value v = new Value();
    v.i = 25;
    second(v,i);
    System.out.println(v.i);
    }
    public void second(Value v,int i) {
    i=0;
    v.i = 20;
    Value val = new Value();
    v = val;
    System.out.println(v.i + " " + i);
    }
    }
    class Value{
    int i=15;
    }

    图例:

  • 相关阅读:
    Java中的多线程
    Service组件
    Notification和Notification Manager的使用
    Java网络编程
    Intent组件
    Android 多任务多线程断点下载
    hdu 2045
    hdu 2492
    poj 2785
    湖南省第六届程序设计大赛D(台球碰撞)
  • 原文地址:https://www.cnblogs.com/buxiang-Christina/p/13330136.html
Copyright © 2011-2022 走看看