Difference between Class and Structure in PHP and Java - java

What is real difference between Class and Structure when you are dealing with Object Oriented Programming. This question is asked many times during my interviews for SE.
Some people says that there is only one difference:
Structure members are public by default and Class members are private by default.
Some says there are many differences.
After reading many articles and forums, I have the following differences:
Classes DEFAULT to having private members. Structures DEFAULT to having public members.
Structures are values type.
Classes are reference type.
Structure stores in memory via stack.
Classes stored in memory via heap.
Structure doesn’t support inheritance.
Classes support inheritance.
Constructor works in different way.
‘new’ operator works in different way.
Allocating memory for structure is very fast because this takes place inline or on the stack.
What are your opinion on my above list or you have a different one. Thanks

This is pretty language-specific. You seem to be mixing a fair share of both C++ and C#, both of which are very different languages (despite superficial similarities in syntax).
In C++ structs indeed default to public member visibility while class defaults to private. In C# struct is used to declare value types which are passed by value (note that the stack allocation is an implementation detail, not a contract).
Generally both languages seem to have the same idea of what struct and class should represent: struct is for simple data structures which do little more than holding data, while classes have state and methods to manipulate it. They are used to build objects in some concrete or abstract sense while data structures are just that: data in a structured form; they don't need to do much with that data or even know what data that is. Essentially they're dumb and don't care.
But that's just how the language designers thought they should be used. People are good at mis-using things so not every struct you see may be a simple, dumb data structure and not every class you see may be a full-blown class with lots of methods and whatnot. It's merely a convention and if people follow it others can look at the code and see "Oh, nice, that's a struct so I don't expect much logic here and move on to more interesting things." It might work ... in theory.
ETA: Since you mentioned in a comment that you are particularly interested in PHP or Java: Both languages do not have any distinction at the syntax or language level of class or struct which is why your question strikes me as a little odd. In both Java and PHP you model things as classes, regardless of whether they are just data structures without logic or actual classes with everything there is.

This is entirely language dependent, so there can be no single correct answer. If you are interested in a specific language, please specify it in your question.

From an OO perspective, there are no difference. They are both types that have a public API with methods (and properties if your language supports them).
From a technical standpoint, there can be many differences, but that depends on the language and/or platform.
When it comes to OO design, I simply choose to ignore that such a thing as a struct exists at all as it gives me no additional capabilities or features. As we dive deeper into the implementation, a class may turn out to be better implemented as a struct, but it's a pure implementation detail.

Difference between Structure and Classes
-The major difference between class and structure is that the declaration of structure
starts with the keyword 'struct' whereas on the other hand, a class starts with the
keyword 'class'.
-In class the data member and member are private by default whereas in structure they
are public by default.
-Data hiding is supported in classes but not in structure.
-Structure deals with variables only whereas objects deal with real-world objects.
-If we explicitly specify the access type of each member, then a structure will behave exactly
as a class.

Related

I want to know the meaning of compile-time decisions

What does it mean to say "with inheritance you're locked into compile-time decisions about code behavior".
I suggest this post from Donal Fellows on Programmers,
Some languages are pretty strongly static, and only allow the
specification of the inheritance relationship between two classes at
the time of definition of those classes. For C++, definition time is
practically the same as compilation time. (It's slightly different in
Java and C#, but not very much.) Other languages allow much more
dynamic reconfiguration of the relationship of classes (and class-like
objects in Javascript) to each other; some go as far as allowing the
class of an existing object to be modified, or the superclass of a
class to be changed. (This can cause total logical chaos, but can also
model real world nasties quite well.)
But it is important to contrast this to composition, where the
relationship between one object and another is not defined by their
class relationship (i.e., their type) but rather by the references
that each has in relation to the other. General composition is a very
powerful and ubiquitous method of arranging objects: when one object
needs to know something about another, it has a reference to that
other object and invokes methods upon it as necessary. As soon as you
start looking for this super-fundamental pattern, you'll find it
absolutely everywhere; the only way to avoid it is to put everything
in one object, which would be massively dumb! (There's also stricter
UML composition/aggregation, but that's not what the GoF book is
talking about there.)
One of the things about the composition relationship is that
particular objects do not need to be hard-bound to each other. The
pattern of concrete objects is very flexible, even in very static
languages like C++. (There is an upside to having things very static:
it is possible to analyse the code more closely and — at least
potentially — issue better code with less overhead.) To recap,
Javascript, as with many other dynamic languages, can pretend it
doesn't use compilation at all; just pretence, of course, but the
fundamental language model doesn't require transformation to a fixed
intermediate format (e.g., a “binary executable on disk”). That
compilation which is done is done at runtime, and can be easily redone
if things vary too much. (The fascinating thing is that such a good
job of compilation can be done, even starting from a very dynamic
basis…)
Some GoF patterns only really make sense in the context of a language
where things are fairly static. That's OK; it just means that not all
forces affecting the pattern are necessarily listed. One of the key
points about studying patterns is that it helps us be aware of these
important differences and caveats. (Other patterns are more universal.
Keep your eyes open for those.)

Aren't classes in Java equivalent to structures in c

I just started learning java yesterday since i want to make android apps. So far i only know c. I am reading a book called "Head first java" and it keeps talking about object and classes which are pretty new to me. I just have one question and if someone can clarify this for me that'd be very helpful:
What is/are the difference(s) between classes(java) and structures(c)?
ps: I'd also love if you can recommend me a book that really is for absolute beginners because the book i'm reading right now doesn't have enough details for those that are completely new to object oriented programming. Thank you.
No. You don't get inheritance, methods, abstract methods, polymorphism, and many more object oriented concepts with Structs.
You can try to make C conform to object oriented behavior using structs, but that's different from using an object oriented language.
"Aren't classes in Java equivalent to structures in c?"
Short answer, No.
My answer is too short cause the differences is the difference between two completely different paradigms, and it needs a complete book (not even a chapter) like : "Thinking in java".
Java classes perform several roles, only one of which is (implicitly) defining the layout of the data structure called the instance of that class, but you are right in thinking that objects are essentially data structures, just like instances of struct.
The main difference is that C's struct is something much more raw and "close to the metal" than a Java class. Basically, with much additional framework code and strict adherence to many conventions you could reimplement a good part of Java's objects, but the syntax would not be as clean as in Java.
There are many other differences, such as what exactly is covered by compiler's static checking, automatic memory management, etc. In the end, differences outweigh similarities, but as a point of understanding, it is not wrong to compare Java objects with C structs.
I know, that I am contradicting the view of a lot of people here, but you are right, a class really is nothing more or less than a struct with a lot of bells and whistles.
To be precise, the C++ language actually specifies that an instance of a class without virtual functions and/or virtual inheritance has the same memory layout as a C struct with the same data members in the same order.
All that is added to the struct to provide runtime polymorphism is a single v-table pointer, which is used to look up the virtual members. Inheritance is generated by including the base class structures as data members of the child class struct.
Of course, when you think about it for a second, you realize that classes must be implemented with structs, one way or another. C++/Java classes must be implemented somehow, after all. And it helps to remind yourself that object orientation is not primarily a language feature, it is a paradigm that can be used in any imperative programming language. It can be used in Java, in C++, in C, in Pascal, in Fortran, and even in assembler. All which the so-called object oriented languages add, is syntactic sugar to handle all the technical stuff of object orientation.
Nevertheless, it is important to learn all the bells and whistles when you start working in C++ or Java.

When is a reference to the object class required?

What is the function of the class Object in java? All the "objects" of any user defined class have the same function as the aforementioned class .So why did the creators of java create this class?
In which situations should one use the class 'Object'?
Since all classes in Java are obligated to derive (directly or indirectly) from Object, it allows for a default implementation for a number of behaviours that are needed or useful for all objects (e.g. conversion to a string, or a hash generation function).
Furthermore, having all objects in the system with a common lineage allows one to work with objects in a general sense. This is very useful for developing all sorts of general applications and utilities. For example, you can build a general purpose cache utility that works with any possible object, without requiring users to implement a special interface.
Pretty much the only time that Object is used raw is when it's used as a lock object (as in Object foo = new Object(); synchronized(foo){...}. The ability to use an object as the subject of a synchronized block is built in to Object, and there's no point to using anything more heavyweight there.
Object provides an interface with functionality that the Java language designers felt all Java objects should provide. You can use Object when you don't know the subtype of a class, and just want to treat it in a generic manner. This was especially important before the Java language had generics support.
There's an interesting post on programmers.stackexchange.com about why this choice was made for .NET, and those decisions most likely hold relevance for the Java language.
What Java implements is sometimes called a "cosmic hierarchy". It means that all classes in Java share a common root.
This has merit by itself, for use in "generic" containers. Without templates or language supported generics these would be harder to implement.
It also provides some basic behaviour that all classes automatically share, like the toString method.
Having this common super class was back in 1996 seen as a bit of a novelty and cool thing, that helped Java get popular (although there were proponents for this cosmic hierarchy as well).

Scala closures compared to Java innerclasses -> final VS var

I've first asked this question about the use of final with anonymous inner classes in Java:
Why do we use final keyword with anonymous inner classes?
I'm actually reading the Scala book of Martin Odersky. It seems Scala simplifies a lot of Java code, but for Scala closures I could notice a significant difference.
While in Java we "simulate" closures with an anonymous inner class, capturing a final variable (which will be copied to live on the heap instead of the stack) , it seems in Scala we can create a closure which can capture a val, but also a var, and thus update it in the closure call!
So it is like we can use a Java anonymous innerclass without the final keyword!
I've not finished reading the book, but for now i didn't find enough information on this language design choice.
Can someone tell me why Martin Odersky, who really seems to take care of function's side effects, choose closures to be able to capture both val and var, instead of only val?
What are the benefits and drawbacks of Java and Scala implementations?
Thanks
Related question:
With Scala closures, when do captured variables start to live on the JVM heap?
An object can be seen a bag of closures that share access to the same environment and that environment is usually mutable. So why make closures generated from anonymous functions less powerful?
Also, other languages with mutable variables and anonymous functions work the same way. Principle of lease astonishment. Java is actually WEIRD in not allowing mutable variables to be captured by inner classes.
And sometimes they're just darn useful. For example a self modifying thunk to create your own variant of lazy or future processing.
Downsides? They have all the downsides of shared mutable state.
Here are some benefits and drawbacks.
There is a principle in language design that the cost of something should be apparent to the programmer. (I first saw this in Holt's Design and Definition of the Turing Language, but I forget the name he gave it.) Two things that look the same should cost the same. Two local vars should have similar costs. This is in Java's favour. Two local vars in Java are implemented the same and so cost the same regardless of whether one of them is mentioned in an inner class. Another point in Java's favour is that in most cases the captured variable is indeed final, so there is little cost to the programmer to be prevented from capturing nonfinal local vars. Also the insistence on final simplifies the compiler, since it means that all local variables are stack variables.
There is another principle of language design that says be orthogonal. If a val can be captured why not a var. As long as there is a sensible interpretation, why put in restrictions. When languages are not orthogonal enough, they seems perverse. On the other-hand, languages that have too much orthogonality may have complex (and hence buggy and/or late and/or few) implementations. For example Algol 68 had orthogonality in spades, but implementing it was not easy, meaning few implementations and little uptake. Pascal (designed at about the same time) had all sorts of inelegant restrictions that made writing compilers easier. The result was lots of implementations and lots of uptake.

C++ and Java : Use of virtual base class

I have some doubts while comparing C++ and Java multiple inheritance.
Even Java uses multiple, multi-level inheritance through interfaces - but why doesnt it use anything like a virtual base class as in C++ ? Is it because the members of a java interface are being ensured one copy in memory (they are public static final), and the methods are only declared and not defined ?
Apart from saving memory, is there any other use of virtual classes in C++ ? Are there any caveats if I forget to use this feature in my multiple inheritance programs ?
This one is a bit philosophical - but why didnt the C++ developers made it a default to make every base class, virtual ? What was the need of providing flexibility ?
Examples will be appreciated. Thanks !!
1) Java interfaces dont have attributes. One reason for virtual base classes in c++ is to prevent duplicate attributes and all the difficulties associated with that.
2) There is at least a slight performance penalty for using virtual base classes in c++. Also, the constructors become so complicated, that it is advised that virtual base classes only have no-argument constructors.
3) Exactly because of the c++ philosphy: One should not require a penalty for something which one may not need.
Sorry - not a Java programmer, so short on details. Still, virtual bases are a refinement of multiple inheritance, which Java designers always defended ommiting on the basis that it's overly complicated and arguably error-prone.
virtual bases aren't just for saving memory - the data is shared by the different objects inheriting from them, so those derived types could use it to coordinate their behaviour in some way. They're not useful all that often, but as an example: object identifiers where you want one id per most-derived object, and not to count all the subobjects. Another example: ensuring that a multiply-derived type can unambiguously map / be converted to a pointer-to-base, keeping it easy to use in functions operating on the base type, or to store in containers of Base*.
As C++ is currently Standardised, a type deriving from two classes can typically expect them to operate independently and as objects of that type tend to do when created on the stack or heap. If everything was virtual, suddenly that independence becomes highly dependent on the types from which they happen to be derived - all sorts of interactions become the default, and derivation itself becomes less useful. So, your question is why not make the default virtual - well, because it's the less intuitive, more dangerous and error-prone of the two modes.
1.Java multiple inheritance in interfaces behaves most like virtual inheritance in C++.
More precisely, to implement java-like inheritance model in c++ you need to use c++ virtual base classes.
However, one of the disadvantages of c++ virtual inheriritance (except of small memory and performance penalty) is the impossibility to static_cast<> from base to derived, so rtti (dynamic_cast) need to be used
(or one may provide "hand made" virtual casting functions for child classes if a list of
such child classes are known in advance)
2.if you forget "virtual" qualifier in inheritance list, it usually lead to compiler error
since any casting frome drived to base class becomes ambigious
3.Philosophical questions usually are quite dificult to answer... c++ is a multiparadigm (and multiphilosophical) language and doesn't impose any philosophical decisions. You may use virtual inheritance whenever possible in you own projects, and (you are rioght) it has a good reason. But such a maxima may be unacceptable for others, so universal c++ tools (standard and other widely used libraries) should be (if possible) free of any particular philosophical conventions.
I'm working on an open source project which basically is translating a large C++ library to Java. The object model of the original creature in C++ can be pretty complicated sometimes. More than necessary, I'd say... which was more or less the motto of Java designers... well... this is another subject.
The point is that I've written an article which shows how you can circumvent type erasure in Java. The article explains well how it can be done and, in the end how your source code can eventually resemble C++ very closely.
http://www.jquantlib.org/index.php/Using_TypeTokens_to_retrieve_generic_parameters
An immediate implication of the study I've done is that it would be possible to implement virtual base classes in your application, I mean: not in Java, not in the language, but in your application, via some tricks, or a lot of tricks to be more precise.
In case you do have interest for such kind of black magic, the lines below may be useful for you somehow. Otherwise certainly not.
Ok. Let's go ahead.
There are several difficulties in Java:
1. Type erasure (solved in the article)
2. javac was not designed to understand what a virtual base class would be;
3. Even using tricks you will not be able to circumvent difficulty #2, because this difficulty appears at compilation time.
If you'd like to use virtual base classes, you can have it with Scala, which basically solved difficulty #2 by exactly creating another compiler, which fully understands some more sophisticated object models, I'd say.
if you'd like to explore my article and try to "circunvent" virtual base classes in pure Java (not Scala), you could do something like I explain below:
Suppose that you have something like this in C++:
template<Base>
public class Extended : Base { ... }
It could be translate to something like this in Java:
public interface Virtual<T> { ... }
public class Extended<B> implements Virtual<B> { ... }
OK. What happens when you instantiate Extended like below?
Extended extended = new Extended<Base>() { /* required anonymous block here */ }
Well.. basically you will be able to get rid of type erasure and will be able to Obtain type information of Base inside your class Extended. See my article for a comprehensive explanation of the black magic.
OK. Once you have type of Base inside Extended, you can instantiate a concrete implementation of Virtual.
Notice that, at compile time, javac can verify types for you, like in the example below:
public interface Virtual<Base> {
public List<Base> getList();
}
public class Extended<Base> implements Virtual<Base> {
#Override
public List<Base> getList() {
// TODO Auto-generated method stub
return null;
}
}
Well... despite all effort to implement it, in the end we are doing badly what an excellent compiler like scalac does much better than us, in particular it is doing its job at compile time.
I hope it helps... if not confused you already!

Categories