>  기사  >  Java  >  Java의 인스턴스 변수

Java의 인스턴스 변수

王林
王林원래의
2024-08-30 15:10:42346검색

자바 프로그램에서는 클래스나 함수에서 객체가 호출될 때마다 인스턴스가 생성되는데, 객체가 호출될 때마다 메모리 저장 단위를 할당할 목적으로 변수를 사용하고, 인스턴스가 생성된다. 인스턴스에서 수행된 모든 변경 사항이나 작업은 인스턴스 변수와 해당 메모리 단위에 자동으로 반영됩니다. 이러한 유형의 변수는 int, char, long, short, boolean, float, double, byte 및 object와 같은 여러 데이터 유형에서 지원됩니다.

구문:

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

<datatype>  <variable_name>;
<datatype>  <variable_name> = <initializing_value>;

변수에는 주로 3가지 유형이 있습니다.

  • 지역변수
  • 인스턴스 변수
  • 클래스/정적 변수

Java의 인스턴스 변수

인스턴스 변수는 클래스 내에서 선언/정의되지만 생성자, 메서드 및 블록 외부에 있습니다. 인스턴스 변수는 인스턴스(객체)에 특정하고 인스턴스(객체) 간에 공유되지 않으며 특정 인스턴스의 변수에 대한 변경 사항이 다른 인스턴스에 반영되지 않기 때문에 그렇게 호출됩니다. 힙의 객체에 메모리가 할당되면 각 인스턴스 변수에 대한 슬롯이 생성됩니다. 객체의 인스턴스 변수는 'new'로 객체를 생성할 때 생성되고 객체가 소멸되면 소멸됩니다. 객체는 이를 사용하여 상태를 보존합니다.

구문:

public class Employee {
public String Name; // instance variable with public Access.
private int salary ; // instance variable with private access.
public static String company; // not an instance variable as it is Static and the value it holds is
//   not instance but class specific.
}

인스턴스 변수 선언

인스턴스 변수에는 기본값이 있습니다. 따라서 지역 변수와 달리 초기화 없이 선언할 수 있습니다. 변수의 기본값은 데이터 유형에 따라 다릅니다.

Datatype Default Value
boolean false
byte 0
short 0
int 0
long 0L
char u0000
float 0.0f
double 0.0d
Object null
데이터 유형 기본값 부울 거짓 바이트 0 짧음 0 정수 0 긴 0L 문자 u0000 부동 0.0f 더블 0.0d 객체 null

Characteristics of Instance Variable in Java

  • Instance variables are visible to the constructor, method(s) and block(s). It is usually recommended to declare them as private, but the users can change the level of visibility by declaring it with various access modifiers suitable for their program.
  • The variable name generally calls instance variables, but when these variables are used within a static method, they should be called using a fully specified name with the variable’s reference.
    Syntax:
    Objectreference.variable_name
  • Instance variables of a base class can be used by the subclasses depending on the access level given to the variable.
  • Instance variables can be declared final to protect the constness of a declared variable. final instance variables are initialized while declaration and can’t be modified. They can also be declared and initialized in block and constructor.
  • The instance variable can use the default access modifier.
  • Instance variables can be declared. If a variable is declared as transient, it is not serialized into a byte stream. Its state changes are not stored. In deserialization, when the object is created back from the byte stream, transient variables hold their respective data type’s default values.
  • Instance variables cannot have abstract, synchronized, strictfp or native modifiers as these are applicable to methods only.
  • Instance variables cannot be declared static if declared, they become class level variables.

Examples of Instance Variable in Java

Examples of the instance variable in java are given below:

Example #1

Code:

import java.io.*;
public class Employee {
// this instance variable can be accessed any child class since it is public.
public String Name;
// Since salary is a private variable, it  is visible in this class only.
private int salary;
// static variable  is same among the instances
public static String company;
// The name variable is initialized in the constructor
public Employee (String eName) {
Name = eName;
}
public void setSalary(int eSal) {
salary = eSal;
}
public void printEmp() {
System.out.println("name  : " + Name );
System.out.println("salary :" + salary);
System.out.println("Company :" + Employee.company);
}
public static void main(String args[]) {
Employee.company = "Google";
Employee employee_one = new Employee("Jack");
employee_one .setSalary(100000);
employee_one .printEmp();
Employee employee_two = new Employee("Jill");
employee_two .setSalary(200000);
employee_two .printEmp();
}
}

Output:

Java의 인스턴스 변수

In the above example, we can see the difference between instance variables and static variables. We have created two objects for employees. The name and salary of the objects are different, but the company is the same for both. This is because it is a static variable and the rest are instance variables.

By changing the line “private int salary; “ in the above code to “ private final int salary = 500;”. We’re changing the behavior of the variable. Since we’re trying to modify a final variable, the compiler throws the following error.

Output:

Java의 인스턴스 변수

Example #2

Code:

import java.io.*;
public class DefaultValues {
boolean val1;
double val2;
float val3;
int val4;
long val5;
String val6;
public static void main(String[] args) {
System.out.println("Default values are :");
DefaultValues d = new DefaultValues();
System.out.println("Val1 = " + d.val1);
System.out.println("Val2 = " + d.val2);
System.out.println("Val3 = " + d.val3);
System.out.println("Val4 = " + d.val4);
System.out.println("Val5 = " + d.val5);
System.out.println("Val6 = " + d.val6);
}
}

The above code snippet on execution results in the below output. As mentioned earlier, instance variables have default values if they are not initialized while declaring. This program prints the default values of all the data types.

Output:

Java의 인스턴스 변수

Example #3

Code:

import java.io.*;
public class Test implements Serializable
{
// Normal variables
int val1 = 10;
int val2 = 20;
// Transient variables
transient int val3 = 30;
// Use of transient has no impact here
transient static int val4 = 40;
transient final int val5 = 50;
public static void main(String[] args) throws Exception
{
Test input = new Test();
// serialization
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(input);
// de-serialization
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Test output = (Test)ois.readObject();
System.out.println("val1 = " + output.val1);
System.out.println("val2 = " + output.val2);
System.out.println("val3 = " + output.val3);
System.out.println("val4 = " + output.val4);
System.out.println("va15 = " + output.val5);
}
}

Executing the above program results in the below-given output. variable val3 is declared transient, so its value was not stored into the byte stream when the Test object was serialized.whereas val4 and val5 are not instance variables because they violate the rules of instance variables. Hence their states remain unaffected.

Output:

Java의 인스턴스 변수

위 내용은 Java의 인스턴스 변수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바의 변수다음 기사:자바의 변수