📜  理解Java中的类和对象

📅  最后修改于: 2022-05-13 01:55:33.598000             🧑  作者: Mango

理解Java中的类和对象

面向对象这一术语解释了将软件组织为包含数据和行为的不同类型对象的组合的概念。因此,面向对象的编程(OOPs)是一种编程模型,它通过提供一些规则来简化软件的开发和维护。程序是围绕对象而不是动作和逻辑组织的。它增加了程序的灵活性和可维护性。理解程序的工作变得更容易,因为 OOP 将数据及其行为(方法)带入单个(对象)位置。

OOP 的基本概念是:

  1. 目的
  2. 班级
  3. 封装
  4. 遗产
  5. 多态性
  6. 抽象

本文讨论Java中的对象

面向对象编程中类和对象的需求

类:类是用户定义的蓝图或原型,从中创建对象。它表示一种类型的所有对象共有的一组属性或方法。 OOP 中需要类,因为:

  • 它提供了创建对象的模板,可以将代码绑定到数据中。
  • 它有方法和数据的定义。
  • 它支持面向对象编程的继承属性,因此可以维护类层次结构。
  • 它有助于维护成员变量的访问规范。

对象:它是面向对象编程的基本单元,它代表了现实生活中的实体。
现实生活中的实体有两个共同特征:它们都有属性和行为。

一个对象包括:

  • 状态:由对象的属性表示。它还显示对象的属性。
  • 行为:它由对象的方法表示。它显示了一个对象与其他对象的响应。
  • 身份:它给一个对象一个唯一的名字。它还授予一个对象与其他对象交互的权限。

OOP 中需要对象,因为可以创建它们来调用非静态函数,该函数不存在于 Main 方法中,但存在于类中,并且还为用于存储数据的空间提供名称。

示例:两个数字相加,需要将两个数字分开存储,以便可以拾取并对其进行所需的操作。因此,创建两个不同的对象来存储这两个数字将是这种情况的理想解决方案。

演示在 OOP 中使用对象和类的示例

空白图 - 第 1 页 (5)

对象与现实世界中发现的事物有关。例如,图形程序可能具有诸如“圆形”、“方形”、“菜单”之类的对象。一个在线购物系统可能有诸如“购物车”、“客户”和“产品”之类的对象。

声明对象(也称为实例化类)

当一个类的对象被创建时,该类被称为实例化。所有实例共享类的属性和行为。但是这些属性的值,即状态对于每个对象都是唯一的。一个类可以有任意数量的实例。

例子 :

空白图 - 第 1 页 (3)

当我们声明变量(类型名称;)时。这会通知编译器我们将使用 name 来引用类型为 type 的数据。对于原始变量,此声明还为变量保留了适当的内存量。所以对于引用变量,类型必须严格地是一个具体的类名。一般来说,我们不能创建抽象类或接口的对象。

Dog tuffy;

如果我们像这样声明引用变量(tuffy),它的值将是不确定的(null),直到一个对象被实际创建并分配给它。简单地声明一个引用变量并不会创建一个对象。

使用new初始化对象

new运算符通过为新对象分配内存并返回对该内存的引用来实例化一个类。 new运算符还调用类构造函数。

Java
// Java program to illustrate the concept
// of classes and objects
 
// Class Declaration
 
public class Dog {
    // Instance Variables
    String name;
    String breed;
    int age;
    String color;
 
    // Constructor Declaration of Class
    public Dog(String name, String breed,
               int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
 
    // method 1
    public String getName()
    {
        return name;
    }
 
    // method 2
    public String getBreed()
    {
        return breed;
    }
 
    // method 3
    public int getAge()
    {
        return age;
    }
 
    // method 4
    public String getColor()
    {
        return color;
    }
 
    @Override
    public String toString()
    {
        return ("Hi my name is " + this.getName() +
          ".\nMy breed, age and color are " + this.getBreed()
           + ", " + this.getAge() + ", " + this.getColor());
    }
 
    public static void main(String[] args)
    {
        Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
        System.out.println(tuffy.toString());
    }
}


Java
// Java program to illustrate the
// creating and accessing objects
// using new keyword
 
// base class
class Dog {
 
    // the class Dog has two fields
    String dogName;
    int dogAge;
 
    // the class Dog has one constructor
    Dog(String name, int age)
    {
        this.dogName = name;
        this.dogAge = age;
    }
}
 
// driver class
public class Test {
    public static void main(String[] args)
    {
        // creating objects of the class Dog
        Dog ob1 = new Dog("Bravo", 4);
        Dog ob2 = new Dog("Oliver", 5);
 
        // accessing the object data through reference
        System.out.println(ob1.dogName + ", " + ob1.dogAge);
        System.out.println(ob2.dogName + ", " + ob2.dogAge);
    }
}


Java
// Java program to demonstrate
// object creation using newInstance() method
 
// Base class
class Example {
    void message()
    {
        System.out.println("Hello Geeks !!");
    }
}
 
// Driver class
class Test {
    public static void main(String args[])
    {
        try {
            Class c = Class.forName("Example");
            Example s = (Example)c.newInstance();
            s.message();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Java
// java program to demonstrate
// creation of object
// using Constructor.newInstance() method
 
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
 
public class ConstructorExample {
 
    // different exception is thrown
    public static void main(String[] args)
        throws NoSuchMethodException,
               SecurityException,
               InstantiationException,
               IllegalAccessException,
               IllegalArgumentException,
               InvocationTargetException
    {
        Constructor constructor = ExampleClass.class
                                      .getConstructor(String.class);
        ExampleClass exampleObject = (ExampleClass)constructor
                                         .newInstance("GeeksForGeeks");
        System.out.println(exampleObject.getemp_name());
    }
}
 
class ExampleClass {
 
    // private variable declared
    private String emp_name;
 
    public ExampleClass(String emp_name)
    {
        this.emp_name = emp_name;
    }
 
    // get method for emp_named to access
    // private variable emp_name
    public String getemp_name()
    {
        return emp_name;
    }
 
    // set method for emp_name to access
    // private variable emp_name
    public void setemp_name(String emp_name)
    {
        this.emp_name = emp_name;
    }
}


Java
// java program to demonstrate
// object creation using clone() method
 
// employee class whose objects are cloned
class Employee implements Cloneable {
    int emp_id;
    String emp_name;
 
    // default constructor
    Employee(String emp_name, int emp_id)
    {
        this.emp_id = emp_id;
        this.emp_name = emp_name;
    }
 
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
// driver class
public class Test {
 
    public static void main(String args[])
    {
 
        try {
            Employee ob1 = new Employee("Tom", 201);
 
            // Creating a new reference variable ob2
            // which is pointing to the same address as ob1
            Employee ob2 = (Employee)ob1.clone();
 
            System.out.println(ob1.emp_id + ", " + ob1.emp_name);
            System.out.println(ob2.emp_id + ", " + ob2.emp_name);
        }
        catch (CloneNotSupportedException c) {
            System.out.println("Exception: " + c);
        }
    }
}


Java
// Java code to demonstrate object
// creation by deserialization
 
import java.io.*;
 
// Base class
class Example implements java.io.Serializable {
 
    public int emp_id;
    public String emp_name;
 
    // Default constructor
    public Example(int emp_id, String emp_name)
    {
        this.emp_id = emp_id;
        this.emp_name = emp_name;
    }
}
 
// Driver class
class Test {
    public static void main(String[] args)
    {
        Example object = new Example(1, "geeksforgeeks");
        String filename = "file1.ser";
 
        // Serialization
        try {
 
            // Saving of object in a file
            FileOutputStream file1 = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file1);
 
            // Method for serialization of object
            out.writeObject(object);
 
            out.close();
            file1.close();
 
            System.out.println("Object has been serialized");
        }
 
        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
 
        Example object1 = null;
 
        // Deserialization
        try {
 
            // Reading object from a file
            FileInputStream file1 = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file1);
 
            // Method for deserialization of object
            object1 = (Example)in.readObject();
 
            in.close();
            file1.close();
 
            System.out.println("Object has been deserialized");
            System.out.println("Employee ID = " + object1.emp_id);
            System.out.println("Employee Name = " + object1.emp_name);
        }
 
        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
 
        catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundException is caught");
        }
    }
}


输出:
Hi my name is tuffy.
My breed, age and color are papillon, 5, white

  • 此类包含一个构造函数。我们可以识别构造函数,因为它的声明使用与类相同的名称并且它没有返回类型。 Java编译器根据参数的数量和类型来区分构造函数。 Dog类中的构造函数有四个参数。以下语句提供“tuffy”、“papillon”、5、“white”作为这些参数的值:
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");

执行此语句的结果可以说明为:

无标题

注意:所有类都至少有一个构造函数。如果一个类没有显式声明, Java编译器会自动提供一个无参数构造函数,也称为默认构造函数。这个默认构造函数调用类父类的无参数构造函数(因为它只包含一个语句,即 super();),或者如果类没有其他父类,则调用Object类构造函数(因为 Object 类是所有类的父类直接或间接)。

创建对象的不同方法

  • 使用 new 关键字:这是创建对象的最简单方法。通过使用此方法,可以调用所需的构造函数。
    句法:
ClassName ReferenceVariable = new ClassName();

Java

// Java program to illustrate the
// creating and accessing objects
// using new keyword
 
// base class
class Dog {
 
    // the class Dog has two fields
    String dogName;
    int dogAge;
 
    // the class Dog has one constructor
    Dog(String name, int age)
    {
        this.dogName = name;
        this.dogAge = age;
    }
}
 
// driver class
public class Test {
    public static void main(String[] args)
    {
        // creating objects of the class Dog
        Dog ob1 = new Dog("Bravo", 4);
        Dog ob2 = new Dog("Oliver", 5);
 
        // accessing the object data through reference
        System.out.println(ob1.dogName + ", " + ob1.dogAge);
        System.out.println(ob2.dogName + ", " + ob2.dogAge);
    }
}
输出:
Bravo, 4
Oliver, 5

  • 使用 Class.newInstance() 方法:用于动态创建新类。它可以调用任何无参数的构造函数。此方法返回调用 newInstance() 方法的类Class对象,该对象将返回作为命令行参数传递的该类的对象。
    引发不同例外的原因:-
    如果传递的类不存在,则会发生ClassNotFoundException
    如果传递的类不包含默认构造函数,则会发生InstantiationException ,因为 newInstance() 方法在内部调用该特定类的默认构造函数。
    如果驱动类没有访问指定类定义的定义,则会发生IllegalAccessException
    句法:
ClassName ReferenceVariable = 
                   (ClassName) Class.forName("PackageName.ClassName").newInstance();

Java

// Java program to demonstrate
// object creation using newInstance() method
 
// Base class
class Example {
    void message()
    {
        System.out.println("Hello Geeks !!");
    }
}
 
// Driver class
class Test {
    public static void main(String args[])
    {
        try {
            Class c = Class.forName("Example");
            Example s = (Example)c.newInstance();
            s.message();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Hello Geeks !!

  • 对 Constructor 类使用 newInstance() 方法:这是一种创建对象的反射方式。通过使用它可以调用参数化和私有构造函数。它用 InvocationTargetException 包装抛出的异常。它被不同的框架使用——Spring、Hibernate、Struts 等。 Constructor.newInstance() 方法优于 Class.newInstance() 方法。
    句法:
Constructor constructor = ClassName.class.getConstructor();
 ClassName ReferenceVariable = constructor.newInstance();

例子:

Java

// java program to demonstrate
// creation of object
// using Constructor.newInstance() method
 
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
 
public class ConstructorExample {
 
    // different exception is thrown
    public static void main(String[] args)
        throws NoSuchMethodException,
               SecurityException,
               InstantiationException,
               IllegalAccessException,
               IllegalArgumentException,
               InvocationTargetException
    {
        Constructor constructor = ExampleClass.class
                                      .getConstructor(String.class);
        ExampleClass exampleObject = (ExampleClass)constructor
                                         .newInstance("GeeksForGeeks");
        System.out.println(exampleObject.getemp_name());
    }
}
 
class ExampleClass {
 
    // private variable declared
    private String emp_name;
 
    public ExampleClass(String emp_name)
    {
        this.emp_name = emp_name;
    }
 
    // get method for emp_named to access
    // private variable emp_name
    public String getemp_name()
    {
        return emp_name;
    }
 
    // set method for emp_name to access
    // private variable emp_name
    public void setemp_name(String emp_name)
    {
        this.emp_name = emp_name;
    }
}
输出:
GeeksForGeeks

  • 使用 clone() 方法:用于克隆对象。这是复制对象的最简单和最有效的方法。在代码中, Java.lang.Cloneable接口必须由要创建其对象克隆的类实现。如果未实现 Cloneable 接口,则 clone() 方法会生成CloneNotSupportedException
    句法:
ClassName ReferenceVariable = (ClassName) ReferenceVariable.clone();

例子:

Java

// java program to demonstrate
// object creation using clone() method
 
// employee class whose objects are cloned
class Employee implements Cloneable {
    int emp_id;
    String emp_name;
 
    // default constructor
    Employee(String emp_name, int emp_id)
    {
        this.emp_id = emp_id;
        this.emp_name = emp_name;
    }
 
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
// driver class
public class Test {
 
    public static void main(String args[])
    {
 
        try {
            Employee ob1 = new Employee("Tom", 201);
 
            // Creating a new reference variable ob2
            // which is pointing to the same address as ob1
            Employee ob2 = (Employee)ob1.clone();
 
            System.out.println(ob1.emp_id + ", " + ob1.emp_name);
            System.out.println(ob2.emp_id + ", " + ob2.emp_name);
        }
        catch (CloneNotSupportedException c) {
            System.out.println("Exception: " + c);
        }
    }
}
输出:
201, Tom
201, Tom

  • 使用反序列化:要反序列化一个对象,首先要在类中实现一个可序列化的接口。此方法中不使用构造函数来创建对象。
    句法:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FileName));
ClassName ReferenceVariable = (ClassName) in.readObject();

例子:

Java

// Java code to demonstrate object
// creation by deserialization
 
import java.io.*;
 
// Base class
class Example implements java.io.Serializable {
 
    public int emp_id;
    public String emp_name;
 
    // Default constructor
    public Example(int emp_id, String emp_name)
    {
        this.emp_id = emp_id;
        this.emp_name = emp_name;
    }
}
 
// Driver class
class Test {
    public static void main(String[] args)
    {
        Example object = new Example(1, "geeksforgeeks");
        String filename = "file1.ser";
 
        // Serialization
        try {
 
            // Saving of object in a file
            FileOutputStream file1 = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file1);
 
            // Method for serialization of object
            out.writeObject(object);
 
            out.close();
            file1.close();
 
            System.out.println("Object has been serialized");
        }
 
        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
 
        Example object1 = null;
 
        // Deserialization
        try {
 
            // Reading object from a file
            FileInputStream file1 = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file1);
 
            // Method for deserialization of object
            object1 = (Example)in.readObject();
 
            in.close();
            file1.close();
 
            System.out.println("Object has been deserialized");
            System.out.println("Employee ID = " + object1.emp_id);
            System.out.println("Employee Name = " + object1.emp_name);
        }
 
        catch (IOException ex) {
            System.out.println("IOException is caught");
        }
 
        catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundException is caught");
        }
    }
}

对象和类的区别