Rumah  >  Artikel  >  Java  >  Pembolehubah Contoh dalam Java

Pembolehubah Contoh dalam Java

王林
王林asal
2024-08-30 15:10:42346semak imbas

Instance dalam program Java dicipta apabila objek dipanggil dalam kelas atau fungsi, yang menggunakan pembolehubah untuk tujuan memperuntukkan unit storan memori untuk setiap kali objek dipanggil dan kejadian dibuat. Sebarang perubahan atau operasi yang dilakukan pada kejadian akan mencerminkan secara automatik dalam pembolehubah contoh dan unit memori yang sepadan. Pembolehubah jenis ini disokong oleh beberapa jenis data, iaitu int, char, long, short, boolean, float, double, byte dan object.

Sintaks:

Mulakan Kursus Pembangunan Perisian Percuma Anda

Pembangunan web, bahasa pengaturcaraan, ujian perisian & lain-lain

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

Terdapat terutamanya 3 jenis pembolehubah:

  • Pembolehubah setempat
  • Pembolehubah tika
  • Pembolehubah Kelas/Statik

Pembolehubah Instance dalam Java

Pembolehubah instance diisytiharkan/ditakrifkan dalam kelas tetapi di luar pembina (s), kaedah(s) dan blok(s). Pembolehubah contoh dipanggil sedemikian kerana ia adalah contoh (objek) khusus dan tidak dikongsi antara kejadian (objek) dan perubahan yang dilakukan kepada pembolehubah bagi kejadian tertentu tidak akan mencerminkan yang lain. Apabila memori diperuntukkan untuk objek dalam timbunan, slot untuk setiap pembolehubah contoh dicipta. Pembolehubah contoh objek dicipta apabila objek dicipta dengan 'baru' dan dimusnahkan apabila objek dimusnahkan. Objek menggunakannya untuk memelihara negeri.

Sintaks:

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.
}

Mengisytiharkan Pembolehubah Contoh

Pembolehubah tika mempunyai nilai lalai; oleh itu, ia boleh diisytiharkan tanpa permulaan, tidak seperti pembolehubah tempatan. Nilai lalai untuk pembolehubah bergantung pada jenis datanya.

Datatype Default Value
boolean false
byte 0
short 0
int 0
long 0L
char u0000
float 0.0f
double 0.0d
Object null
Jenis data
Nilai Lalai
boolean salah
bait 0
pendek 0
int 0
panjang 0L
char u0000
terapung 0.0f
double 0.0d
Objek 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:

Pembolehubah Contoh dalam 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:

Pembolehubah Contoh dalam 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:

Pembolehubah Contoh dalam 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:

Pembolehubah Contoh dalam Java

Atas ialah kandungan terperinci Pembolehubah Contoh dalam Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Pembolehubah dalam JawaArtikel seterusnya:Pembolehubah dalam Jawa