Assignment operator and "this" keyword - java

Consider the following code snippet:
class Parent {
Parent() {
this = new Child();
}
}
class Child extends Parent { }
The above would throw a syntax error: The left hand side of an assignment operator must be a variable
In java, the this keyword stores the memory address of the current calling object. I wish to overwrite the current object with an instance of the class' subclass. I understand the above snippet is throwing an error as this is not a variable and is probably immutable.
However, I wish to know why java doesn't allow this above feature? Is there any downside to it?
EDIT: This question occurred to me with reference to a Natural Language Processing (NLP) context. For example, in the French language, every verb has to end with 'er', 'ir' or 're'. All verbs have certain features in common. However, every verb must be either one of the three types mentioned above. So in the constructor of the parent class 'Verb', I want to categorize the object created as an 'ErVerb', 'IrVerb' or 'ReVerb'.

There are two scenarios:
If you let this be instantiated to any Object whatsoever, not necessarily one in the type hierarchy, then an instantiation would have no guarantee about the contents of its reference. This breaks a couple things, most notably the entire concept of object-oriented programming.
If you restrict this to be instantiated to any subclass of the parent class, then that subclass constructor would call the parent constructor infinitely many times, causing a StackOverflowError.

It doesn't make any sense to construct a subclass instance inside the parent's constructor and substitute the actual parent instance with the created child instance.
Despite the nasty StackOverflowError pointed out in the comments and in the other answer, there's no use case for doing this. In general, it's absurd (from the logical point of view) to create a child while creating the parent.
Consider the following reasoning:
A specific car is being assembled in a factory. The process to assemble a specific car consists of many steps.
Some of these steps only occur when assembling the specific car, while others occur both when assembling the specific car and when assembling other vehicles, such as a specific van.
Now let's suppose that one of these general steps that occur when assembling many vehicles (including both the specific car and the specific van), indicates that we must assemble a new specific van and let it be the general vehicle being assembled.
Now, the specific car we were assembling would have become this new specific van. But it's impossible for a car to be a van => ABSURD.

Related

Need to make different objects in the same array react differently

I am making a method to use on a array that has objects from 3 child classes of the same parent class. I want two of the classes to react differently, when third class does a certain action. Would I use a loop on the array with a .getClass() and a if-else-if statement as to what to do with each of the objects based off of the .getClass()?
While that would theoretically work, using if-else-if switches based on class's type is often considered a code smell.
There isn't a lot of extra info you give as to what sort of behavior and reaction you're looking for but as first step consider this: Can the "reaction" you want to get from the classes reasonably be considered to be a method of the class, and could it be a method of the parent class that the child classes override as needed?
(Think of the classical example with a class Animal and a method makeSound() and then a class Dog that overrides it to output Bark! and a class Cat that overrides it to output Meow!)
You might check here for a few ideas: https://refactoring.guru/smells/switch-statements
or provide extra info so we can figure out a good refactoring to avoid the switch block.

Java, why are objects known as instances of a class?

Classes are a software bundle of variables and functions, also known as a blueprint that defines the variables and methods common to objects of a certain kind. So why are objects also known as instances of a class?
Like you said, class is a blueprint; objects are made using those blueprints.
Its like you have a blueprint of a car - you have one blueprint, but many cars based on that blueprint.
According to dictionary.com: An instance is - "an example or single occurrence of something"
An object is a single occurrence or realization of a class.
Class is a syntactic notion, governed by compile time rules, such as naming, scope, etc. That your program defines a class A means that 1) you have a type, and 2) that the right class loader will be able to find A's bytecode on the classpath. But it doesn't mean that your running program is able to operate on this class. An operable object with its own state must be first instantiated with new, which, at run time, will cause the classloader to allocate memory required to hold that state. You can have any number of objects of a single class A, all of type A but with their own state memory.

Is polymorphism an imminent side effect of inheritance?

Can inheritance exist without Polymorphism or is it an imminent side effect of it? It might be a fallacious question, but it will help me understand the relation between both.
Can inheritance exist without Polymorphism?
They are related concepts, but yes, it is possible to have one without the other. In Java if you subclass a parent class you also get a subtype, but in other languages this might not be the case implicitly. In some languages inheritance can be just a form of code reuse.
For example, in C++ you don't get polymorphism if you don't mark your methods virtual. See here for an explanation: Why do we need Virtual Functions in C++?. In Java on the other hand, all public methods are implicitly virtual.
This is a vast subject that has many flavors in many languages. As a TL;DR (and a gross gross gross simplification) you can think inheritance is a form of code reuse while polymorphism is the ability to substitute an object of a type with an object of a subtype and your program continues to work correctly. In Java these two things overlap and you get one from the other but not all languages are like that.
And even if you get polymorphism out of the box from inheritance it is still possible to "break polymorphism" by not respecting the Liskov substitution principle. Like I said... a vast subject.
If you look closely they are actually related to each other, because its Inheritance which makes Polymorphism possible, without any relationship between two class, it's not possible to write polymorphic code, which can take advantage of runtime binding of different objects.
You cannot use Polymorphism on something which is not inherited by Child class e.g. private method can't be overridden in Java.
Like in real world, Inheritance is used to define the relationship between two classes. It's similar to Father-Son relationship. In object oriented programming, we have a Parent class (also known as the super class) and a Child class (also known as the subclass). Similar to the real world, Child inherits Parents qualities, e.g. it's attribute, methods and code. Inheritance is actually meant for code-reuse. A child can reuse all the codes written in Parent class, and only write code for behavior which is different than the parent. Though it’s possible to restrict something to parent itself by using the private and final keyword in Java.On the other hand, Polymorphism is an ability of Object to behave in multiple form.
Read more: http://java67.blogspot.com/2014/04/difference-between-polymorphism-and-Inheritance-java-oops.html#ixzz4A201Ln9T
And from the following topic
Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person, Student won't see it because its private, and private fields are not visible to subclasses.
Polymorphism deals with how the program decides which methods it
should use, depending on what type of thing it has. If you have a
Person, which has a read method, and you have a Student which extends
Person, which has its own implementation of read, which method gets
called is determined for you by the runtime, depending if you have a
Person or a Student. It gets a bit tricky, but if you do something
like
Person p = new Student();
p.read();
the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.

Is it bad practice to have an empty intermediary class in a class Hierarchy?

I am writing a dense hierarchy of classes all deriving from a single abstract parent class for a project that will need to make use of polymorphism, and also to trace objects through the class hierarchy. I have determined that a cluster of classes are the same, in that they could all have an abstract parent class which is a child of the overall parent. However, for the purposes of the project, there is no need to implement anything in this class that isn't already defined in its parent. I have decided to create the class and leave it empty, as I feel it would be useful in narrowing down precisely what kind of object the program is dealing with at run time. Is this bad practice?
In certain cases, this is fully acceptable. I've done this before; it mostly involved empty classes which would specify certain generic parameters, so they were not "really" empty, as the type parameters narrowed the base class down a bit.

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.

Categories