Is a class an instance of an object? - java

Is a class an instance of an object?
Can you create many objects from the same class, and can a class have many instances?
Thank you for your help, I'm reading a book on Java programming and am currently confused about these definitions.

A "class" conceptually is not an object (or an "instance of an object", which makes no sense really), but rather a sort of blueprint from which objects are created. Objects are instances of classes. You can indeed instantiate a class many times.
Don't confuse this with instances of the Class class, which are objects (e.g. String.class, int.class etc.).

A class describes the structure of an object and is not an instance.
An instance is an object that conforms to the structure defined by the class.
There can be many instances of a class.
For example, consider a "Person" class. When creating the class, you could say, "A person may have a first name or a last name," but you're not creating an actual person, you're just saying what makes up a person. When you create a person, you create an instance of the class "Person" and you may have many people, which means having many instances of the class "Person".

The CLASS works as a BLUEPRINT which allows you to create OBJECTS based on this BLUEPRINT.
You CAN create many instances (OBJECTS) of the same CLASS.
To clarify:
Object - Objects have states and behaviors. Example: A dog has states
- color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blue print that describes
the behaviors/states that object of its type support.

A class is not an instance of an object. In fact, an object is an instance of a class. Here is the explanation,
Conceptually, each class represents and describes the characteristics of an independent concept in a program. these characteristics are also owned by any object of this class type. Usually, instance variables of a class defines properties of an entity. For example, if you have a class called Student, then obviously this class should have instance variables that represents student's characteristics such as name, level, grade...etc. Also, it can have methods like getGrade (), getName (). Now, any object of type Student will have the properties defined by its class (eg. name, level..), meaning the information stated in the class is encapsulated in its objects. Also, this object can be used to reach for the methods like getGrade or getName (again because these methods are encapsulated inside each object).
The class is the definition of a single concept structure, and the object is an implementation of this structure. That's why, we say, an object is an instance of a class. Note that we can have various instances (objects) of a single class, each object will encapsulate the same structure defined by its class, but with different values. For example, you may have several objects of the class Student each represents a different student with different name, level, grade...etc. Although these objects are different, they share the same structure, meaning they are all students.
Data encapsulation provided by class/object technique is really useful. Suppose you have 100 students who you need to store their names, levels, and any other related information. Instead of defining 100 String variables to store each student name, and 100 int variables to store the levels, you simply create a class which defines a student structure and create as many objects as you want. It saves both time and effort, and it makes debugging much easier.

Related

Why is a class called an abstraction of an object?

I understand that a class is essentially a blueprint of an object, but the idea that a class is an 'abstraction' of an object is a little hard for me to wrap my head around... If anyone could tell me the real meaning of the statement: "A class is an abstraction of an object", I'd be really grateful.
My confusion is because this statement has been interpreted differently by different people...
Does 'abstraction' mean:
Dealing with the basics of a system, and not the deep intricacies of that system?
or does it mean that:
Only an abstract class can be considered an abstraction of an object?
Thanks in advance,
Abhigyan
A class is a description of everything that will be in a certain type of object. For instance, a car will have a steering wheel, seats, dashboard, etc and functions such as accelerating, stopping etc. Each individual car is a car object, but the conceptual car is analogous to the class.
Dealing with the basics of a system, and not the deep intricacies of that system?
Somewhat, since a class does not usually describe exactly what goes into each field (for instance, the color of the steering wheel)
Only an abstract class can be considered an abstraction of an object?
No, this is more general that the abstract keyword in Java.
Basically, a class is an abstraction because it describes what is created, whereas an object is created itself.
A class can be instantiated into objects. It captures the characteristics that are common to all these objects.
A class defines fields & behavior (methods). It is instantiated into objects, which hold concrete values for those fields.
Abstraction as a term is used at many levels -- most commonly in regard of behavior. However in this regard it is being used of value.
We could state more clearly: A class is an abstraction across the possible values of its instances.
Example in pseudocode:
public class Cat {
String name;
String color;
}
object Cat ("Missy", "grey");
object Cat ("Whiskers", "orange");
object Cat ("Fluffy", "black");
As we see, class abstracts over values of its instances.

Should I use static methods for a menu class in a employee payroll console system?

My program is a small program that has an employee class and another Menu class that is used to manipulate an array of employees in the console program. Should the methods of the Menu class be declared static?
Some examples of the methods are addEmployee, updateEmployee and showEmployees. Every employee object is stored in an Employees array, which will be used by many other methods, such as to show all employees by passing in the array.
If the methods are declared static, then all I have to do is to pass in the array into the static methods is such as
Employee[] employees = new Employee[50];
Menu.showEmployees(Employees);
//other example methods that manipulate the array
Menu.methodX(Employees);
Menu.methodY(Employees);
Menu.methodZ(Employees);
However, if not static, I have in mind to have a constructor for the Menu class that would take in an employees array, after which the menu object can manipulate the array directly as its member:
Employee[] employees = new Employee[50];
Menu menu1 = new Menu(Employees);
menu1.showEmployees();
//other example methods that manipulate the array
menu1.methodX();
menu1.methodY();
menu1.methodZ();
I am aware that static methods should only be used as utility methods, but sometimes static methods can be used if convenient and if the system is not going to expand. Which is the better practice in this case?
A static method is useful for invoking functions on a class that don't require state. The most venerable example of this is Integer.parseInt; we don't require an instance of an Integer to parse a String into an int.
If you find yourself passing the state repeatedly to static functions, it's a wiser move to use an instance as opposed to all-static functions/variables. Specifically in this case, since your operations absolutely do depend on state, then having static functions makes little sense.
...some examples of the methods are addEmployee, updateEmployee and
showEmployees. Every employee object is stored in an Employees array,
which will be used by many other methods, such as to show all
employees by passing in the array.
Here is a general rule:
Avoid global state.
Global state makes your programs fragile, insecure, and difficult to maintain. Global state is the anti-thesis of encapsulation (which describes the principle in which data is hidden inside modular, decoupled units).
Global state is primarily made up of the static instance fields of a class. Observing the rule above, the answer to your question depends on how your data model is defined:
Employee data stored in static instance fields. In this case, your static employee methods will be able to directly access and modify the static employee data. You should not do this, however. It is bad design. Any code that has access to your class can access and alter employee data causing security problems, consistency problems, and maintenance problems.
Employee data stored in non-static instance fields. In this case, your static methods cannot directly access the non-static employee data. To solve this, you can pass a reference to the instance you wish to modify as an argument to the method. There will still be possible concurrency problems and these will need to be considered in a multithreaded design. This design has better encapsulation, should be less fragile, and more secure.
The best design would be to carefully construct a domain object model. Your goal should be to have each module encapsulate all of the state and the behavior that operates on that state. In this way, you should find that your goals can be accomplished without as many static methods. As a benefit, your program will contain modules that are decoupled, can evolve independently, are easier to maintain, and are more secure.
The fact that you have a Menu class suggests that your design may be suboptimal. A Menu has no obvious relationship to an Employee; it does not make intuituitive sense that a Menu -has an- Employee. Your classes are probably not as decoupled as they could be.
I think ,dear ,u should use static...bcz if u specify any method static ...u need not to create an object of the class to call the method .. U can directly call it by using (class_name.method_name) ...it saves memory that was being waste into creating an object. Both method are right.......but I have to tell another thing that in java Menu class is a static class. ...so u have to use static keyword to methods

Will objects of a custom class, inside an array, keep their data after serialization?

I am building a small application for keeping statistical data of some sort. I have a general question, before I start coding hard in this matter.
Say we have an object X of its own class, representing a sports match. It has several fields, among which is another object Y - also it's own class. Y will represent stats for a given game. The structure should be something like:
class Match {
Date date;
String venue;
ArrayList<Game>[10] gameList;
...
}
class Game{
int result;
int blah blah;
...
}
If I go and create a couple of Match objects, stored in an array for example, i can serialize an object, that contains this array of Matches, but when i deserialize it back, will I be able to keep the data inside the Game objects for example? Do I need to make each class used Serializable?
The reason for my worries are those lines from the JAVA Api Documentation:
During deserialization, the fields of non-serializable classes will
be initialized using the public or protected no-arg constructor of the
class. A no-arg constructor must be accessible to the subclass that is
serializable. The fields of serializable subclasses will be restored
from the stream.
When traversing a graph, an object may be encountered that does not
support the Serializable interface. In this case the
NotSerializableException will be thrown and will identify the class of
the non-serializable object.
Yes, you need to make Match class serializable. Making a class serialize means that you need to make all instance variables of that class serializable too (notice the recursive definition). In your example, to make Match class serializable, you need to make Game class serializable.
i guess the term
non-serializable classes
means such class doesn't implements the serializable interface there's exist classes in java doesn't implement serializable interface and you can't serialize them for example java.awt.BasicStroke you can't serialize any instance of of this class directly

Need to clear a minute concept about inheritance in general and its implementation in OOP. Please see

I am curious as to how the concept of "inheritance" takes place in the world of object oriented programming. Let me explain my dilemma (I came across this dilemma while studying Java but I hope that my question is generic in nature) :
Suppose there is a class A and a class B. Class A "inherits" Class B. What does this actually mean? Does the compiler make a "new" class, which is THEN instantiated into an object which contains the elements of both the classes A and B behind the scenes? If that's the case, then how are the access restrictions implemented according to the access specifiers?
For a moment, I wondered if it happens in the following manner :
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
But then, it occurred to me that there is a fault with this theory. Suppose two different classes, B and C are inheriting class A. Then, if we are going to make objects of class B and class C, then they'll have their OWN copies of the elements of class A. So this theory fails too.
I was just trying to explain the confusion about inheritance that I have in my mind. It's giving me headache. Please help.
EDIT : This is a link to a discussion related to my question which i found on this site.
Do subclasses inherit private fields?
I may fail, but I'm going to take a stab at an explanation on this for you.
In honesty, I think you may be making what is really a very classic mistake in how you conceive object programming - and that's making the distinction between objects and classes. Object creation in virtually any object-oriented language is one of construction based on a class definition. From your question, it sounds as though you are mentally modeling an OO language in general and object inheritance in particular as aggregating discrete objects, where in reality the objects are being defined in terms of aggregated class definitions.
public class A
{
public A();
}
public class B:A
{
public B();
}
public class C:B
{
public C();
}
In your A->B->C model, C's definition is in terms of its own unique properties plus all the members of its immediate ancestor, B, which, in turn, is defined in terms of its own unique properties plus all the members of its immediate ancestor, A. The process of creating the object is still a unique and discrete event, and the object, despite its multi-layered heritage, is still only one object at instantiation time.
Regarding the visibility of certain members: When a class author designs and builds a class, he makes certain decisions about what he makes available in two distinct perspectives: that which is exposed to consumers of the class, and that which is exposed or available to subclasses. Members and fields declared private are every bit a part of descendant classes, even if they are "contractually" forbidden to be accessed by subclasses. You could make a crude analogy that a TV has a "public" interface of an on/off button, volume control, and color controls, but has "internal" controls not intended for the consumer such as the internal electronic components, or the power supply. They're still very much there even though they are not "visible" or "available" to consumers or subclasses.
Now, that said, there are constructs in most OO languages that reflect the properties you describe - multiple objects - and that involve a design pattern known as Composition (or, sometimes, Aggregation. This is where a class isn't derived from an ancestor class - typically because the class is declared "sealed" (C#) or "final" (Java) (or other designation that prohibits inheritance). That forces a developer interested in using the class to make it a member of another class, such that when the an object of the class is instantiated, you DO have discrete objects of both classes.
You might have the following:
public final class InterestingThing
{
//definitions
public InterestingThing()
}
public final class MyThing
{
InterestingThing _interestingThing = new InterestingThing();
public MyThing()
}
This is very much the kind of scenario you were describing in your original question, in which the creation of MyThing implies the distinct creation of an InterestingThing. Keep in mind, too this structure is generally forced by the design and definition of the original class of interest.
Ultimately, objects are defined by their classes, and multiply-inherited classes are still just a class, but in a refined, hopefully increasingly robust, hierarchy based on good, incremental object design.
I hope, in some way, this explanation helps to answer your question.
Class A "inherits" Class B. What does this actually mean?
If class A extends class B, it inherits all members (fields and methods) of B, i.e. class A will have these members even through they are not declared in the body of class A.
Whether class A is permitted to access a particular member is an unrelated matter.
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
No. A single object of class A is created. That object just happens to have all inherited members, too. For instance, if you have:
class B {
private int x;
}
class A extends B {
private int y;
}
The runtime will store, for every object of class A, the value of x and the value of y.
That code in class A does not access the value of x is enforced by verifying that the source code of A does not use the name x upon compilation, and by verifying that the bytecode of A does not refer to the field x upon loading the class at runtime. Put differently, access modifiers are independent of memory layout.

Instance Vs Object

When we have base and sub class in java, and we instantiate the sub class, we get one instance or two instances? If we get two objects, how many instances we get? Does one instance holds the two objects of base and sub class or two separate instances?
If you instantiate a subclass, you will get just one object/instance. This single instance will contain all of the fields of the subclass (which includes the fields defined by its parent classes).
Remember that subclasses means that you're defining a new class which derives from an existing parent, that is it inherits those definitions. So if the parent declares a field called id, the subclass will also have a field called id, and so an instantiation of that subclass will contain an id field. This field is declared in the parent class, but it does belong to the subclass.
If you instantiate the subclass, there is no instantiation of the parent. No object exists whose runtime class is the parent class.
(I'm not sure what your distinction is between "object" and "instance" in your question. You've used them in a way that implies they are different, but typically they mean exactly the same thing. An object is an instance of a particular class.)
You get a single instance that is of the two classes - the base and the subclass.
Try to understand it with this example: there is a class Mammal and the class Human. You belong to both of them - nevertheless, there is a single instance of yourself. If there were two persons in the room, you would have two instances of both classes!
Instance == object ... both are the same, just 2 different names. If you create one object (maybe a subclass) you get one object.
When we have base and sub class in java, and we instantiate the sub
class, we get one instance or two instances?
We get one instance because each Java class instance is contained in a single object.
If we get two objects, how many instances we get?
The term "instance" is synonymous to object. Saying one instance is just a different way of saying one object.
Does one instance holds the two objects of base and sub class or two
separate instances?
No. Java compiler creates class bytecode that contains the functionality of both base and extension, so instantiating that class results in a single object.
What is then the logical difference between instance and object?
In the context that you are using these words, there is no difference. An instance (of a class) is an object, and vice-versa.
However, in the broader context, an instance (of a type) is not necessarily an object - it depends on the type. For instance that you could say that 42 is an "instance" of the int type.
new classA(); //Here you create an instance of a class
classA ob //create object named "ob" and datatype "classA"
And now we assign the instance to the object
classA ob = new classA();
like
int num = 10

Categories