:静态成员既可以通过对象名来访问,也可以通过类名直接访问它。
时间: 2023-06-12 10:07:33 浏览: 49
是的,静态成员包括静态变量和静态函数,可以通过对象名或者类名来访问它们。使用对象名访问静态成员,实际上是使用对象所属的类来访问静态成员;使用类名访问静态成员,是直接访问静态成员。静态成员函数没有 this 指针,因此不能直接访问非静态成员。而静态成员变量是所有对象所共享的,因此在访问时不需要创建对象,可以直接使用类名来访问。
相关问题
java静态成员既可以通过对象名来访问,也可以通过类名直接访问它
是的,Java中的静态成员(静态变量和静态方法)可以通过对象名来访问,也可以通过类名直接访问它。但是建议使用类名来直接访问静态成员,因为静态成员是与类绑定的,而不是与对象绑定的,如果通过对象访问静态成员,可能会给其他程序员造成混淆和误解。例如:
```
public class MyClass {
public static int myStaticVariable = 10;
public int myNonStaticVariable = 20;
}
MyClass obj = new MyClass();
System.out.println(obj.myStaticVariable); // 通过对象名访问静态变量
System.out.println(MyClass.myStaticVariable); // 通过类名直接访问静态变量
```
上述代码可以通过对象名和类名都来访问静态变量 `myStaticVariable`,但是建议使用类名来访问静态变量。
c语言java静态成员既可以通过对象名来访问,也可以通过类名直接访问它
在 C 语言中,静态成员(即静态变量和静态函数)可以通过类名和对象名来访问。但是在 Java 中,静态成员只能通过类名来访问,不能通过对象名来访问。
在 C 语言中,静态成员在内存中只有一份副本,无论创建多少个对象,都共享这份副本。因此,可以通过类名和对象名来访问静态成员变量和静态成员函数。例如:
```c
#include <stdio.h>
struct Student {
int id;
char name[20];
static int count; // 静态成员变量
static void printCount() { // 静态成员函数
printf("count = %d\n", count);
}
};
int Student::count = 0; // 静态成员变量初始化
int main() {
Student s1, s2;
s1.id = 1001;
s2.id = 1002;
Student::count = 2; // 通过类名访问静态成员变量
s1.count = 3; // 通过对象名访问静态成员变量
s1.printCount(); // 通过对象名访问静态成员函数
Student::printCount(); // 通过类名访问静态成员函数
return 0;
}
```
在 Java 中,静态成员变量和静态成员方法属于类本身,而不是对象实例。因此,只能通过类名来访问静态成员,不能通过对象名来访问。例如:
```java
class Student {
int id;
String name;
static int count; // 静态成员变量
static void printCount() { // 静态成员方法
System.out.println("count = " + count);
}
}
int main() {
Student s1 = new Student();
Student s2 = new Student();
s1.id = 1001;
s2.id = 1002;
Student.count = 2; // 通过类名访问静态成员变量
// s1.count = 3; // 错误:不能通过对象名访问静态成员变量
s1.printCount(); // 错误:不能通过对象名访问静态成员方法
Student.printCount(); // 通过类名访问静态成员方法
return 0;
}
```