JavaToday

两个问题记录

面向对象编程中的“方法”和“函数”

有必要理解下面向对象编程中的“方法”和“函数”,这里参考伯乐在线的最佳答案,顺便理解下不同编程语言的情况;

下面先来看看被选为最佳答案的回复(来自 Andrew Edgecombe ):

  • 函数是一段代码,通过名字来进行调用。它能将一些数据(参数)传递进去进行处理,然后返回一些数据(返回值),也可以没有返回值。

  • 所有传递给函数的数据都是显式传递的。

    • 1.方法也是一段代码,也通过名字来进行调用,但它跟一个对象相关联。方法和函数大致上是相同的,但有两个主要的不同之处;
    • 2.方法中的数据是隐式传递的;
  • 方法可以操作类内部的数据(请记住,对象是类的实例化–类定义了一个数据类型,而对象是该数据类型的一个实例化)

  • 以上只是简略的解释,忽略了作用域之类的问题。

接着是Raffi KhatchadourianAndrew Edgecombe 答案的补充:

  • 对于 1),你应当再加上“ 方法在 C++ 中是被称为成员函数”。因此,在 C++ 中的“方法”和“函数”的区别,就是“成员函数”和“函数”的区别。此外,诸如 Java 一类的编程语言只有“方法”。所以这时候就是“静态方法”和“方法”直接的区别。

  • 对于2),你应当补上方法可以操作已在类中声明的私有实例(成员)数据。其他代码都可以访问公共实例数据。

Aaron 的回答:

  • 方法和对象相关;

  • 函数和对象无关。

  • Java中只有方法,C中只有函数,而C++里取决于是否在类中。

Java实现进制的转换(16进制转换算法)

十进制—–>>>>>二进制(32位)—–>>>>>十六进制({‘0’,’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,’A’,’B’,’C’,’D’,’E’,’F’}

java代码实现,列举了5种方法,最终解决输出的情况最佳的是动态数组(^–^ ^–^ ^–^ ^–^),不得不佩服强大的动态数组啊,有点Matlab的感觉了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.ArrayList;
/**
* Created by vampire on 2017/5/3.
*/
public class JavaHexad_conver {
public static void main(String[] args){
toHex(60);
System.out.println();
toHex1(60);
System.out.println();
toHex2(60);
System.out.println();
toHex3(60);//动态数组才是完美的啊
System.out.println();
toHex4(60);
}
private static void toHex4(int num){
char[] hex={'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
char[] result=new char[8];
int i=0;
while(num!=0){
int temp=num&15;
result[i]=hex[temp];
i++;
num=num>>>4;
}
for(int x=result.length-1;x>=0;x--){
System.out.print(result[x]);
}
}
/*
引入动态数组搞定
*/
private static void toHex3(int num){
char[] hex={'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
ArrayList result=new ArrayList();
while(num!=0){
int temp=num&15;
result.add(hex[temp]);
num=num>>>4;
}
for(int x=result.size()-1;x>=0;x--){
char temp1=(char)(result.get(x));
System.out.print(temp1);
}
}
//
private static void toHex2(int num){
char[] hex={'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
char[] result=new char[8];
for(int x=0;x<8;x++){
int temp=num & 15;
result[x]=hex[temp];
num=num>>>4;
}
for(int y=7;y>=0;y--){
System.out.print(result[y]);
}
}
//获取一个整数的16进制表现形式
/*
什么时候使用数组?
如果数据出现了对应关系,而且对应关系的一方是有序的数字编号,并作为角标使用,这时就要考虑数组的使用。
*/
private static void toHex1(int num){
char[] hex={'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
for(int x=0;x<8;x++){
int temp=num & 15;
System.out.print(hex[temp]);
num=num>>>4;
}
}
private static void toHex(int num){
for(int x=0;x<8;x++){
int temp=num & 15;
if(temp<9){
System.out.print(temp);
}else{
System.out.print((char)(temp-10+'A'));
}
num=num>>>4;
}
}
}
您的支持将鼓励我继续向前!