[Java Programming Tutorial] Detailed explanation of objects and classes in Java

On this page, we'll learn about Java objects and classes. In object-oriented programming techniques, we use objects and classes to design programs.

Objects in Java are both physical and logical entities whereas classes in Java are only logical entities.

What is an object in Java

Entities that have state and behavior are called objects, such as chairs, bicycles, markers, pens, tables, cars, and so on. It can be physical or logical (tangible and intangible). An example of an intangible object is a banking system.

An object has three characteristics:

  • Attribute: Represents the data (value) of an object.
  • Method: Represents a method (function) of an object, such as deposit, withdrawal, etc.
  • Identity: Object identity is usually achieved through a unique ID. The value of ID is not visible to external users. However, it is used internally by the JVM to uniquely identify each object.

For example, Pen is an object. Its name is Reynolds; its color is white, called its state. It is for writing, so writing is its act.

Objects are instances of classes. A class is a template or blueprint for creating objects. Therefore, an object is an instance (result) of a class.

Object definition:

  • Objects are entities in the real world.
  • Objects are runtime entities.
  • Objects are entities with state and behavior.
  • The object is an instance of a class.

What is a class in Java

A class is a group of objects with common properties. It is a template or blueprint for creating objects. It is a logical entity. It cannot be physical.

A class in Java can contain:

  • field
  • method
  • constructor
  • Nested classes and interfaces

Syntax for declaring a class:


class <class_name>{
    
      
    field;  
    method;  
}  

Instance variables in Java

Variables created inside a class but outside a method are called instance variables. Instance variables do not acquire memory at compile time. It acquires memory at runtime when an object or instance is created. That's why it's called an instance variable.

methods in Java

In Java, a method is like a function and is used to expose the behavior of an object.

method advantage

  • code reuse
  • Code optimization

New keywords in Java

The new keyword is used to allocate memory at runtime. All objects get memory in the heap memory area.

Object and class example: main in a class

In this example, we create a Student class with two data members id and name. We are creating an object of Student class by new keyword and printing the value of the object.

Here, we create a main() method in the class.

File: Student.java


//Java程序来说明如何定义一个类和字段 
//定义一个学生类  
class Student{
    
      
 //定义字段  
 int id;//字段或数据成员或实例变量  
 //在Student类中创建main方法 
 public static void main(String args[]){
    
      
  //创建对象或实例 
  Student s1=new Student();//创建学生对象 
  //打印对象的值 
  System.out.println(s1.id);//通过引用变量访问成员 
  System.out.println(s1.name);  
 }  
}  

output:

0
null

Object and class example: main outside a class

In live development we create class and use it from another class. This is a better way than before.

Let's see a simple example where we have main() method in another class.

We can have multiple classes in different Java files or in a single Java file. If you define multiple classes in a single Java source file, it is best to use the class name with a main() method to hold the file name.

File: TestStudent1.java


//Java 程序来演示在其中有 main 方法  
//另一个类 
//创建学生类
class Student{
    
      
 int id;  
 String name;  
}  
//创建另一个包含主要方法的类TestStudent1 
class TestStudent1{
    
      
 public static void main(String args[]){
    
      
  Student s1=new Student();  
  System.out.println(s1.id);  
  System.out.println(s1.name);  
 }  
}  

output:

0
null

3 ways to initialize an object

There are 3 ways of initializing objects in Java.

  • by reference variable
  • by method
  • via the constructor

1) Object and class example: initialization by reference

Initializing an object means storing data into the object. Let's look at a simple example where we will initialize an object by reference to a variable.

File: TestStudent2.java


class Student{
    
      
 int id;  
 String name;  
}
class TestStudent2{
    
      
 public static void main(String args[]){
    
      
  Student s1=new Student();  
  s1.id=101;  
  s1.name="小明";  
  System.out.println(s1.id+" "+s1.name);//用空格打印成员
 }  
}  

output:

101 Xiao Ming

We can also create multiple objects and store information in them through reference variables.

File: TestStudent3.java


class Student{
    
      
 int id;  
 String name;  
}  
class TestStudent3{
    
      
 public static void main(String args[]){
    
      
  //创建对象  
  Student s1=new Student();  
  Student s2=new Student();  
  //初始化对象  
  s1.id=101;  
  s1.name="小明";  
  s2.id=102;  
  s2.name="小华";  
  //Printing data  
  System.out.println(s1.id+" "+s1.name);  
  System.out.println(s2.id+" "+s2.name);  
 }  
}  

output:

101 Xiaoming
102 Xiaohua

2) Object and class example: initialization by method

In this example, we create two objects of the Student class and initialize values ​​to these objects by calling the insertRecord method. Here, we display the state (data) of the object by calling the displayInformation() method.

File: TestStudent4.java


class Student{
    
      
 int rollno;  
 String name;  
 void insertRecord(int r, String n){
    
      
  rollno=r;  
  name=n;  
 }  
 void displayInformation(){
    
    System.out.println(rollno+" "+name);}  
}  
class TestStudent4{
    
      
 public static void main(String args[]){
    
      
  Student s1=new Student();  
  Student s2=new Student();  
  s1.insertRecord(111,"小可");  
  s2.insertRecord(222,"小艾");  
  s1.displayInformation();  
  s2.displayInformation();  
 }  
}  

output:

111 Xiaoke222
Xiaoai

insert image description here
As you can see from the figure above, the object acquires the memory in the heap memory area. Reference variables refer to objects allocated in the heap memory area. Here, both s1 and s2 are reference variables, referring to objects allocated in memory.

3) Object and Class Example: Initialization via Constructor

We'll learn about constructors in Java later.

Object and Class Example: Employee

Let's look at an example of maintaining employee records.

File: TestEmployee.java

class Employee{
    
      
    int id;  
    String name;  
    float salary;  
    void insert(int i, String n, float s) {
    
      
        id=i;  
        name=n;  
        salary=s;  
    }  
    void display(){
    
    System.out.println(id+" "+name+" "+salary);}  
}  
public class TestEmployee {
    
      
public static void main(String[] args) {
    
      
    Employee e1=new Employee();  
    Employee e2=new Employee();  
    Employee e3=new Employee();  
    e1.insert(101,"A",45000);  
    e2.insert(102,"B",25000);  
    e3.insert(103,"C",55000);  
    e1.display();  
    e2.display();  
    e3.display();  
}  
}  

output:

101 A 45000.0
102 B 25000.0
103 C 55000.0

Object and Class Example: Rectangle

Another example of maintaining records for the Rectangle class is given.

File: TestRectangle1.java


class Rectangle{
    
      
 int length;  
 int width;  
 void insert(int l, int w){
    
      
  length=l;  
  width=w;  
 }  
 void calculateArea(){
    
    System.out.println(length*width);}  
}  
class TestRectangle1{
    
      
 public static void main(String args[]){
    
      
  Rectangle r1=new Rectangle();  
  Rectangle r2=new Rectangle();  
  r1.insert(11,5);  
  r2.insert(3,15);  
  r1.calculateArea();  
  r2.calculateArea();  
}  
}  

output:

55
45

What are the different ways of creating objects in Java?

There are many ways to create objects in java. they are:

  • by new keyword
  • Through the newInstance() method
  • via the clone() method
  • via deserialization
  • via factory methods etc.

We'll learn about these object creation methods later on.

anonymous object

Anonymous just means nameless. Objects without references are called anonymous objects. It can only be used when creating an object.

Anonymous objects are a good way to go if you only need to use an object once. For example:


new Calculation();//匿名对象

Calling a method by reference:

Calculation c=new Calculation();
c.fact(5)

Call a method through an anonymous object


new Calculation().fact(5);  

Let's see a complete example of anonymous objects in Java.


class Calculation{
    
      
 void fact(int  n){
    
      
  int fact=1;  
  for(int i=1;i<=n;i++){
    
      
   fact=fact*i;  
  }  
 System.out.println("阶乘为 "+fact);  
}  
public static void main(String args[]){
    
      
 new Calculation().fact(5);//使用匿名对象调用方法 
}  
}  

output:

factorial is 120

Create multiple objects by only one type

We can only create multiple objects from a type, like we did in the case of primitives.

Initialization of primitive variables:


int a=10, b=20;

Initialization of reference variables:

1. Rectangle r1= new Rectangle(), r2= new Rectangle(); //Create two objects


Rectangle r1=new Rectangle(), r2=new Rectangle();//创建两个对象

Let's look at this example:


//Java程序来说明其中Rectangle类的使用 
//有长度和宽度数据成员 
class Rectangle{
    
      
 int length;  
 int width;  
 void insert(int l,int w){
    
      
  length=l;  
  width=w;  
 }  
 void calculateArea(){
    
    System.out.println(length*width);}  
}  
class TestRectangle2{
    
      
 public static void main(String args[]){
    
      
  Rectangle r1=new Rectangle(),r2=new Rectangle();//创建两个对象 
  r1.insert(11,5);  
  r2.insert(3,15);  
  r1.calculateArea();  
  r2.calculateArea();  
}  
}  

output:

55
45

Real World Example: Accounts

File: TestAccount.java


//用于演示银行系统工作的Java程序 
//我们从我们的账户存入和提取金额的地方。 
//创建一个具有 deposit() 和 withdraw() 方法的 Account 类  
class Account{
    
      
int acc_no;  
String name;  
float amount;  
//初始化对象的方法
void insert(int a,String n,float amt){
    
      
acc_no=a;  
name=n;  
amount=amt;  
}  
//存款方法
void deposit(float amt){
    
      
amount=amount+amt;  
System.out.println(amt+" 存入");  
}  
//撤回方法  
void withdraw(float amt){
    
      
if(amount<amt){
    
      
System.out.println("余额不足");  
}else{
    
      
amount=amount-amt;  
System.out.println(amt+" 撤回");  
}  
}  
//查询账户余额的方法
void checkBalance(){
    
    System.out.println("余额为: "+amount);}  
//显示对象值的方法   
void display(){
    
    System.out.println(acc_no+" "+name+" "+amount);}
}  
//创建一个测试类来存取金额    
class TestAccount{
    
      
public static void main(String[] args){
    
      
Account a1=new Account();  
a1.insert(832345,"小安",1000);  
a1.display();  
a1.checkBalance();  
a1.deposit(40000);  
a1.checkBalance();  
a1.withdraw(15000);  
a1.checkBalance();  
}}   

output:

832345 Xiaoan 1000.0
balance: 1000.0
40000.0 Deposit
balance: 41000.0
15000.0 Withdraw
balance: 26000.0

Guess you like

Origin blog.csdn.net/2201_75506216/article/details/131836537