📜  从C到Java的面向对象编程的简要概述和比较

📅  最后修改于: 2021-05-25 21:24:29             🧑  作者: Mango

在本文中,您将能够思考OOP如何通过C在Java真正起作用。

通过C,您将了解PolymorphismInheritanceEncapsulationClassObjects等概念。您还知道C语言不支持OOP,但是我们可以通过将精细结构定义为Class和来理解其背后的概念。创建其作为对象的身份。

在Parallel中,通过Java,我们可以了解它如何与实际的Class&Object一起真正地工作。

通过此比较,我们可以思考面向对象编程背后的逻辑。

了解比较的概念

Java

C

Class in java (example Customer) A Structure created in C (example customer)
Fields of the Class (example int id, String name) Variable present in Structure (example int id, char* name)
Constructor present in Class Function created and returning a pointer which is storing the data in heap memory (Example cust* createCustomer)
Method of the class (Example printCustomer) Function created (Example printCustomer)
Creation of Object form the Class in Java Create an instance of struct customer
C
// Adding the necessary header files
#include 
#include 
  
// customer structure
typedef struct customer {
    int id;
    char* name;
  
    // cust is an alias used for struct customer by using
    // typedef
} cust;
  
cust* createCustomer(int id, char* name)
{
    // Memory allocation in the Heap
    cust* this = (cust*)malloc(sizeof(cust));
  
    // Similiar to 'this' in Java
    this->id = id;
    this->name = name;
    return this;
}
void printCustomer(cust* c)
{
    printf("The Id is %d\n", c->id);
    printf("The name is %s\n", c->name);
}
  
int main()
{
    // Create an instance of struct customer Similar
    // to creation of Object form the Class in Java
    cust* c1;
  
    // Adding the Arguments in the function
    // is similar to adding arguments in methods of the Java
    // Class
    c1 = createCustomer(25, "Siddharth");
  
    // Calling the funtion printCustomer
    printCustomer(c1);
  
    // Free the allocated memory
    free(c1);
  
    return 0;
}


Java
// import the required classes
  
import java.io.*;
  
class Cust {
    int id;
    String name;
  
    // constructor
    Cust(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
    public void printCustomer()
    {
        System.out.println("The Id is " + id);
        System.out.println("The name is " + name);
    }
}
  
class GFG {
    public static void main(String[] args)
    {
        // Object declaration
        Cust c1;
  
        // object Initialisation
        c1 = new Cust(25, "Siddharth");
  
        // Calling the method of cust
        // class
        c1.printCustomer();
    }
}


输出
The Id is 25
The name is Siddharth