OOP - Are constructors required? - java

So I was watching a youtube video and the youtuber said: "When you are creating 'this' object, you are going to need to set it to a new ' type ' of this object"...
The class was called objectIntro and the constructor was:
public objectIntro(){
//Object Constructor (Method)
}
So here's my question...
I tried to create an object which basically tells me about the level of petrol with in a car...
public class car {
double petrolLevel;
double tankSize;
public void refillPetrol(double I){
if(I>tankSize){
I = tankSize;
petrolLevel = petrolLevel + I;
}
else{
petrolLevel = petrolLevel + I;
}
}
public void fuelConsumption(double O){
if(O>tankSize){
O=tankSize;
petrolLevel = petrolLevel - O;
}
else{
petrolLevel = petrolLevel - O;
}
}
public String returnPetrolLevel(){
return String.format("%sL", petrolLevel);
}
}
Then the class in which the object is created is...
public class carObject {
public static void main(String[] args){
car object1 = new car();
object1.tankSize = 50;//Litres
object1.petrolLevel = 0;
object1.refillPetrol(50);
object1.fuelConsumption(20);
object1.returnPetrolLevel();
System.out.printf("Petrol Level: %s", object1.returnPetrolLevel());
}
}
My question is, how come my object works without a constructor?
In the car class, I do not have a method which says "public car(){
}", whereas the youtuber stated this would be required?
Could someone clear this up, also I think I am not using the term constructor and method in the write context, could someone explain the definition of these terms, along with some examples.
Thanks

It's all in the Java tutorial
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.
Also the convention is to uppercase your class names, lowercase your method parameters and use getters/setters for member variables which usually are private.
Sometimes you actually might notice that you cannot do new MyClass() or well that you cannot instantiate and object with new at all. This sometimes happens because the coder provided a no-arg private constructor. This is done when for instance you want the user to instantiate the object using a factory method (that you provide in that class) etc. But still doesn't change the fact that the constructor has to be there (that's part of the language spec).
If you want to know more about the default constructor you can consult the java language spec.

If you do not have a constructor there is an implicit constructor that sets all the members to their default value, e.g. 0 for int
The difference between a constructor and a method is the constructor creates and initializes an object while a method is for an object that already exists. You can think of a constructor as a function that is being called on your newly created object to initialize the data in some way.

JLS takes a special care of a class without constructor:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
This means that if you don't write any constructor for your class, one will be provided for you by the compiler and all class members will be initialized to default values by Java Virtual Machine.
But once you write a constructor, only that one will be used to create a class instance.
This behavior is usually good for a class that serves as a data structure, while normal class will have some constructor defined with default initialization code.

The answer to your question is, if you do not provide a constructor to a class the JVM will implicitly call the default constructor which has no parameter.
For detailed information about constructor you can refer below link
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Even if you do not explicitly create a constructor in the class, a default constructor will be created during compile time and used.
https://msdn.microsoft.com/en-us/library/aa645608(v=vs.71).aspx

Related

How is a child object constructed in Java?

In java, how is a child object constructed?
I just started inheritance and these few points are not very clear to me:
Does the child object depend only on the child class' constructor, or does it also depend on the parent's constructor? I need some details about that point.
Also, is super() always called by default in a child constructor?
Any other information regarding this topic is appreciated.
I don't think "A child object" is a good way to think about this.
You're making an object. Like all objects, it is an instance of some specific class, (After all, new SomeInterface() does not compile) and like (almost) all objects, it is made because some code someplace (doesn't have to be your code, of course) ran the java expression new SomeSpecificClass(args); somewhere.
We could say it is a 'child object' because SomeSpecificClass is a child class of some other class.
But that's rather useless. That means the only way to ever make a new 'non-child' object would be to write new Object(); - after all, all classes except java.lang.Object are a child class: If you write public class Foo {}, java will interpret that exactly the same as if you had written public class Foo extends java.lang.Object {}, after all.
So, barring useless* irrelevancies, all objects are child objects, and therefore as a term, 'child object', I'd not use that.
That also means that ALL object creation goes through this 'okay and in what order and how do the constructors work' song and dance routine.
How it works is probably most easily explained by desugaring it all. Javac (the compiler) injects things if you choose to omit them, because a lot of things that feel optional (such as a constructor, a super call, or an extend clause), at the class file / JVM level, aren't**.
Sugar #1 - extends clause
Already covered: if you have no extends clause on your class def, javac injects extends java.lang.Object for you.
Sugar #2 - no super call in constructor
A constructor must either call some specific super constructor on its very first line, or, it it must call some other constructor from the same class on its very first line (this(arg1, arg2);). If you don't, java will inject it for you:
public MyClass(String arg) { this.arg = arg; }
// is treated as:
public MyClass(String arg) {
super();
this.arg = arg;
}
Notably including a compiler error if your parent class has no zero-arg constructor available.
Sugar #3: No constructor
If you write a class that has no constructor, then java makes one for you:
public YourClass() {}
It will be public, it will have no args, and it will have no code on it. However, as per sugar #2 rule, this then gets expanded even further, to:
public YourClass() {super();}
Field inits and code blocks get rewritten to a single block.
The constructor isn't the only thing that runs when you make new objects. Imagine this code:
public class Example {
private final long now = System.currentTimeMillis();
}
This code works; you can compile it. You can make new instances of Example, and the now field will hold the time as it was when you invoked new Example(). So how does that work? That feels a lot like constructor code, no?
Well, this is how it works: Go through the source file top to bottom and find every non-static initializing code you can find:
public class Example {
int x = foo(); // all non-constant initial values count
{
x = 10;
// this bizarre constructor is legal java, and also
// counts as an initializer.
}
}
and then move all that over to the one and only initializer that classes get, in the order you saw them.
Ordering
So, via sugar rules we have reduced ALL classes to adhere to the following rules:
ALL classes have a parent class.
ALL classes have at least 1 constructor.
ALL constructors invoke either another constructor or a constructor from parent.
There is one 'initializer' code block.
Now the only question is, in what order are things executed?
The answer is crazy. Hold on to your hats.
This is the order:
First, set all fields to 0/false/null of the entire 'construct' (the construct involves every field from Child all the way down to Object, of course).
Start with the actual constructor invoked on Child. Run it directly, which means, start with the first line, which neccessarily is either a this() or a super() invocation.
Evaluate the entire line, notably, evaluate all expressions passed as arguments. Even if those are themselves invocations of other methods. But, javac will do some minor effort to try to prevent you from accessing your fields (because those are all uninitialized! I haven't mentioned initializers yet!!).
Yeah, really. This means this:
public class Example {
private final long x = System.currentTimeMillis();
public Example() {
super(x); // x will be .... 0
// how's that for 'final'?
}
}
This will either end up invoking the first line of some other constructor of yours (which is itself also either a this() or a super() call). Either we never get out of this forest and a stack overflow error aborts our attempt to create this object (because we have a loop of constructors that endlessly invoke each other), or, at some point, we run into a super() call, which means we now go to our parent class and repeat this entire song and dance routine once more.
We keep going, all the way to java.lang.Object, which by way of hardcoding, has no this() or super() call at all and is the only one that does.
Then, we stop first. Now the job is to run the rest of the code in the constructor of j.l.Object, but first, we run Object's initializer.
Then, object's constructor runs all the rest of the code in it.
Then, Parent's initializer is run. And then the rest of the parent constructor that was used. and if parent has been shifting sideways (this() invokes in its constructors), those are all run in reverse order as normal in method invocations.
We finally end up at Child; its initializer runs, then the constructor(s) run in order, and finally we're done.
Show me!
class Parent {
/* some utility methods so we can run this stuff */
static int print(String in) {
System.out.println("#" + in);
return 0;
// we use this to observe the flow.
// as this is a static method it has no bearing on constructor calls.
}
public static void main(String[] args) {
new Child(1, 2);
}
/* actual relevant code follows */
Parent(int arg) {
print("Parent-ctr");
print("the result of getNow: " + getNow());
}
int y = print("Parent-init");
long getNow() { return 10; }
}
class Child extends Parent {
Child(int a, int b) {
this(print("Child-ctr1-firstline"));
print("Child-ctr1-secondline");
}
int x = print("Child-init");
Child(int a) {
super(print("Child-ctr2-firstline"));
print("Child-ctr2-secondline");
}
final long now = System.currentTimeMillis();
#Override long getNow() { return now; }
}
and now for the great puzzler. Apply the above rules and try to figure out what this will print.
#Child-ctr1-firstline
#Child-ctr2-firstline
#Parent-init
#Parent-ctr
#the result of getNow: 0
#Child-init
#Child-ctr2-secondline
#Child-ctr1-secondline
Constructor execution ordering is effectively: the first line goes first, and the rest goes last.
a final field was 0, even though it seems like it should never be 0.
You always end up running your parent's constructor.
--
*) You can use them for locks or sentinel pointer values. Let's say 'mostly useless'.
**) You can hack a class file so that it describes a class without a parent class (not even j.l.Object); that's how java.lang.Object's class file works. But you can't make javac make this, you'd have to hack it together, and such a thing would be quite crazy and has no real useful purpose.
In inheritance, the construction of a child object depends on at least one parent constructor.
Calling the super () method is not mandatory. By default, Java will call the parent constructor without argument except if you precise a custom constructor.
Here an example
Mother
public class Mother {
int a;
public Mother() {
System.out.println("Mother without argument");
a = 1;
}
public Mother(int a) {
System.out.println("Mother with argument");
this.a = a;
}
}
child
public class Child extends Mother {
public Child() {
System.out.println("Child without argument");
}
public Child(int a) {
super(a);
System.out.println("Child with argument");
}
}
If you do this :
Child c1 = new Child();
you will get :
Mother without argument
Child without argument
If you do this :
Child c1 = new Child(a);
You will get :
Mother with argument
Child with argument
But if you change the second child constructor to and remove the super(arg) the parent constructor without argument will be called :
public Child(int a) {
// super(a);
System.out.println("Child with argument");
}
You will get :
Mother without argument
Child with argument
May be this course for beginners can help you Coursera java inheritance

Strugling with the keyword this in Java

I've read a lot of explanations for the use of keyword 'this' in java but still don't completely understand it. Do i use it in this example:
private void login_BActionPerformed(java.awt.event.ActionEvent evt) {
if(user_TF.getText().equals("admin")&& pass_PF.getText().equals("admin")){
this.B.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Warning!", "InfoBox: "+"Warning", JOptionPane.INFORMATION_MESSAGE);
}
this.user_TF.setText("");
this.pass_PF.setText("");
}
It's supposed to open a new window if a user and pass match. Do i use 'this' keyword anywhere here?
I think there are two main usages you should know:
If you have a class variable with name N, and a method variable with name N, then to distinguish them, use this.N for class variable and N for method variable. Screenshot displaying possible usage
Imagine you have 2 constructors. One takes String name, another takes name + age. Instead of duplicating code, just use this() to call another constructor. Another screenshot displaying the usage
In your case, I don't see any LOCAL (method) variables of name 'B', so I guess you can do without it.
Any non static method of the class needs an object of that class to be invoked. Class has the blueprint of the state and behavior to modify and read the state. Object is the realization of this blueprint. Once object is created , it has those states and methods.
Suppose you have below code.
public class A{
int property;
public void foo(){
bar();
}
public void bar(){
property = 40;
}
}
public class B{
public static void main(String[] args){
A obj = new A();
obj.foo();
}
}
Lets try to answer few questions.
Q1. Inside the mwthod foo we invoke bar , we have not used any explicit object to invoke it (with . dot operator), upon which object is the method bar invoked.
Q2. Method bar tries to access and modify the variable named property. Which object does this state called property belong to ?
Answers
A1. Object referred by A.this (it is same as this) . It is the object which has invoked foo method which is implicitly made available insode the called method. The object upon which execution of the method takes places can be accessed by this.
A2. same as answer to Q1.
The object at anytime can be accessed by Classname.this inside the non static methods or blocks of the class.

Method overriding can have different number of parameters in subclass and parent class ?Can the no.of parameters differ?

We have parent class and child class having common method testparent() but there is difference in parameters
//Parent Class
public class Overriding {
int a,b,c;
//Parameters are different in number
public void testParent(int i, int j) {
System.out.println(a+b);
}
}
//Child Class Extending Parent Class Method
class ChildOverriding extends Overriding {
int c;
public void testParent(int i,int j,int k) {
System.out.println(a+b+c);
}
//Main Is not getting executed????
public static void main(String args[]) {
Overriding obj = new ChildOverriding();
obj.testParent(1,4,8);
}
}
}
Overriding Means sub class should have same signature of base class method.
Parameters and return type should be the same.
Actually your problem here is that you're accessing a method from SubClass over a reference object of a SuperClass.
Let me explain little bit more.
Super obj = new Sub();
This line will create one reference variable (of class Super) named obj and store it in stack memory and instance of new Sub() with all implementation details will be stored in heap memory area. So after that memory address of instance stored in heap is linked to reference variable stored in stack memory.
obj.someMethod()
Now when we call any method (like someMethod) on reference variable obj it will search for method signature in Super class but when it calls implementation of someMethod it will call it from instance stored in heap memory area.
That's the reason behind not allowing mapping from Super to Sub class (like Sub obj = new Super();) becuase Sub class may have more specific method signature that can be called but instance stored in heap area may not have implementation of that called method.
So your program is giving error just because it isn't able to find method signature that you're calling in super class.
Just remember Java will always look for method signature in type of reference object only.
Answer to your question is Yes, we can have different number of parameters in subclass's method but then it won't titled as method overloading/overriding. because overloading means you're adding new behaviour and overriding means changing the behaviour.
Sorry for my bad English, and if I'm wrong somewhere please let me know as I'm learning Java.
Thanks. :)
You can have the two methods, but then the one in ChildOverriding are not overriding the one in Overriding. They are two independent methods.
To fix your compilation problem, you have to either declare obj ChildOverriding
ChildOverriding obj = new ChilOverriding();
or you have to also implement a three-argument method in Overriding

Calling Constructor Multiple times

How to call the Constructor multiple times using the same object
class a
{
a(int i)
{
System.out.println(i);
}
public static void main(String args[])
{
a b = new a();
int x = 10;
while( x > 0)
{
//Needed to pass the x value to constructor muliple times
}
}
}
I needed to pass the parameter to that constructor.
Constructor of a class A constructs the objects of class A.
Construction of an object happens only once, and after that you can modify the state of the object using methods (functions).
Also notice if programmer does not write any constructor in his class then the Java compiler puts the constructor for the class (public constructor without any parameters) on its own.
In the case where a constructor has been provided by the programmer, the compiler does not create a default constructor. It assumes, the programmer knows and wants creation of the objects of his/her class as per the signature of the explicit constructor.
Constructor calls are chained. Suppose there exists below class relationship.
Child.java extends Parent.java and Parent.java extends GrandParent.java.
Now if Child child = new Child(); is done, only one object is created and that is of Child.java, but the object also has all of the features of GrandParent first then with the features of the Parent and then the Child.
Hence first constructor of GrandParent.java is called then Parent.java is called and lastly the constructor of Child.java is called.
Constructors are special and different from other methods.
The intent of constructors is to create the object, so each time you use the new operator, the constructor is called and a new object is created. You can not call the constructor directly. You need the new operator to call it. Even if you see some class defining methods like getInstance(), it still uses the new operator to construct the object and return the created object.
*PS there are ways to create an object without calling constructor (like Serialization) but that is out of context of the discussion here.
Constructors are called only once at the time of the creation of the object.
Can you please be specific about what you want to achieve?
But I think you could try one of the following two things.
Calling the constructor to create a new object and assigning it to the object 'b':
b = new a(1);
Using the setter method:
void setI(int i){
this.i = i;
}
b.setI(1);
int x = 10;
while( x > 0)
{
a b = new a(x);
}

Get object's class and its constructor, Reflection in Android

suppose i have classA and classB(generic), reference http://www.exampledepot.com/egs/java.lang.reflect/Constructors.html
I am passing a customobject from classA to classB, now i am wanting constructor of customobject in classB and call it
classA
customclass objCustomclass;
classB mClassB;
mClassB.getConstructorAndCall(objCustomclass);
classB
public void getConstructorAndCall(Object objCustomclass);
try {
Object filledObject = objCustomclass.getClass().newInstance();
// here i need to call filledObject's contructor
} catch (Exception e) { }
I am able to create object as the instance of custom object but what about constructor.
note: getConstructorAndCall() is a commom method and in that object is of unknown type that means any class can pass its object.
Thanks.
well if the constructor is empty, then I think that what you have should run the constructor. Anything more complicated, like, passing parameters to the function can be done through:
Constructor[] constructors = objCustomClass.getClass().getConstructors()
for (int i = 0; i < constructors.length; i++) {
Constructor c = constructors[i];
Class[] paramTypes = c.getParameterTypes();
Object[] params;
// do fancy stuff here - it helps if you know what the constructors take beforehand
Object filledObject = c.newInstance(params);
}
Constructor with parameters
From the JavaDoc for java.lang.Class ( http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#newInstance() ):
Creates a new instance of the class represented by this Class object.
The class is instantiated as if by a new expression with an empty
argument list. The class is initialized if it has not already been
initialized.
I. E. the newInstance() method always uses the default constructor.
Most times I see people using new instance and requiring a particular constructor or signature, it happens to be due to a lack on the solution design. You might want to double check if a pattern applies to the solution you need.

Categories