سؤال

Hi I am searching through the net and got stuck on a big question where I can't find the answer so I'm wondering if someone here can help me.

In object-oriented programming concepts class and instance. Instances are also called objects, and has given its name to the programming mode.

I'm also wondering if someone can relate the class and instance to another, and explain what distinguishes these concepts and their different usage.

هل كانت مفيدة؟

المحلول

Well consider the classic example of class Car, It has few attributes like tyres, makeYear, color.

public class Car {
     private int tyres;
     private String makeYear;
     private String color;

     public Car(String color, int tyres, String makeYear) {
         this.tyres = tyres;
         this.makeYear = makeYear;
         this.color = color;
     }

     //Getters and Setters
}

Now there can be multiple instances of car each depicting certain state, say for example, Car1 is red in color, 4 types and 2012 as makeYear and Car2 is blue in color, 5 tyres and 2000 as makeYear. So using instances we can give the states to this Car class.

Something like:

 Car car1 = new Car ("red", 4, "2012");
 Car car2 = new Car ("blue", 5, "2000");

نصائح أخرى

A class is a template or a blueprint from which individual objects are created.

For example, if you own a Baseball, then your baseball is an instance/object of the class of objects known as Baseballs.

So an object is a representation of a real world object, like the "January 2013 edition Top Gear Magazine" and a class is a blueprint which defines objects, like "Magazines".

an Instance is a perticular state of a class For example public class point {public int x; public int y} is a class and point Origin=new point(){x=0,y=0}; is a state of a class . it is called an instance of the class

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top