Java Class with constructor asking for user input [duplicate] - java

I wrote this simple class in java just for testing some of its features.
public class class1 {
public static Integer value=0;
public class1() {
da();
}
public int da() {
class1.value=class1.value+1;
return 5;
}
public static void main(String[] args) {
class1 h = new class1();
class1 h2 = new class1();
System.out.println(class1.value);
}
}
The output is:
2
But in this code:
public class class1 {
public static Integer value=0;
public void class1() {
da();
}
public int da() {
class1.value=class1.value+1;
return 5;
}
public static void main(String[] args) {
class1 h = new class1();
class1 h2 = new class1();
System.out.println(class1.value);
}
}
The output of this code is:
0
So why doesn't, when I use void in the constructor method declaration, the static field of the class doesn't change any more?

In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor, not even if it declares that returns a void. Note the difference here:
public class SomeClass {
public SomeClass() {
//constructor
}
public void SomeClass() {
//a method, NOT a constructor
}
}
Also, if a class doesn't define a constructor, then the compiler will automatically add a default constructor for you.

public void class1() is not a constructor, it is a void method whose name happens to match the class name. It is never called. Instead java creates a default constructor (since you have not created one), which does nothing.

Using void in the constructor by definition leads it to not longer be the constructor.
The constructor specifically has no return type. While void doesn't return a value in the strictest sense of the word, it is still considered a return type.
In the second example (where you use the void), you would have to do h.class1() for the method to get called because it is no longer the constructor. Or you could just remove the void.

This is arguably a design flaw in Java.
class MyClass {
// this is a constructor
MyClass() {...}
// this is an instance method
void MyClass() {...}
}
Perfectly legal. Probably shouldn't be, but is.
In your example, class1() is never getting called, because it's not a constructor. Instead, the default constructor is getting called.
Suggestion: familiarize yourself with Java naming conventions. Class names should start with uppercase.

The reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the run time.
Here is an article explaining this in greater detail:
https://www.quora.com/Why-is-the-return-type-of-constructor-not-void-while-the-return-type-of-a-function-can-be-void

Related

What is the equivalent of :: operator in java?

When accessing a function from another class in c++,
we can write: classA::fct();
Is there an equivalent operator in java?
If not, how can we access a function from another class in java?
Well the ::-operator (Scope Resolution Operator) in C++ allows you to resolve ambiguous calls/references to identifiers. However, in java there are no independent functions as all functions are actually methods (members) of a class. As such there are no need for this operator, have a look here for differences between Java and C++ classes.
I am guessing you are attempting to access a member (possibly static) of a class, in which case you'd use the .-operator as exemplified in Mwesigye's answer or as follows:
public class AB {
public static void main(String[] args) {
B myB = new B();
myB.printA();
}
}
public class A {
public static int getInt() {
return 4;
}
}
public class B {
public void printA() {
System.out.println(A.getInt()); // output: 4
}
}
Here the .-operator is used to access printA() from the instantiated object myB (instantiated from class B). It is also used to access the static method getInt() whose implementation is tied to class A rather than any object of A. More info can be found here.
Take an example of a Class Student with methods what you call functions in c++
eg.
class Student{
//a non static method
public void getFees(){
//your logic
}
public static void deleteSubject(){
// your logic
}
}
class Club{
//create a new instance of student class
Student student = new Student();
public void printData(){
//access a non static method
student.getFees();
//accessing a static method
new Student().deleteSubject();
}
}
Hope this will help.

How to force my subclass constructor not to call base class constructor?

public class Base {
public Base() {
foo();
}
public void foo() {
System.out.println("Base.foo()");
}
}
public class Derived extends Base {
public Derived () {}
public void foo() {
System.out.println("Derived.foo()");
}
}
And then, when i call those:
public class Running {
public static void main(String[] args) {
Base b = new Base();
Derived d = new Derived();
}
}
It outputs:
*Base.foo()*
*Derived.foo()*
So why, when it gets to derived constructor, it invokes the base constructor but uses the derived's method instead?
PS: If I mark those methods as private, it will print out:
*Base.foo()*
*Base.foo()*
This is how Java works read this page https://docs.oracle.com/javase/tutorial/java/IandI/super.html
And more specifically the Note here :
Note: If a constructor does not explicitly invoke a superclass
constructor, the Java compiler automatically inserts a call to the
no-argument constructor of the superclass. If the super class does not
have a no-argument constructor, you will get a compile-time error.
Object does have such a constructor, so if Object is the only
superclass, there is no problem.
So as you can see this is expected behavior. Even though you dot have a super call it is still automatically inserting it.
In regards of the second Question even though you are within the super constructor body still you Instance is of the Subtype. Also if you have some familiarity with C++ read this Can you write virtual functions / methods in Java?
The reason why it will write the base class when marking with private is because private methods are not Inherited. This is part of the Inheritance in Java topic.
To answer the question in your title. As I said, you cannot avoid the base class constructor being called (or one of the base class constructors if it has more than one). You can of course easily avoid the body of the constructor being executed. For example like this:
public class Base {
public Base(boolean executeConstructorBody) {
if (executeConstructorBody) {
foo();
}
}
public void foo() {
System.out.println("Base.foo()");
}
}
public class Derived extends Base {
public Derived() {
super(false);
}
public void foo() {
System.out.println("Derived.foo()");
}
}
public class Running {
public static void main(String[] args) {
Base b = new Base(true);
Derived d = new Derived();
}
}
Now the main method prints only:
Base.foo()
Because in the contructor of the Derived class it automatically gets injected a call to super(), if you do not add a call to super or to other constructor in the same class (using this).

Is it possible to have a constructor with void return type?

I would like to know whether it is possible to have a constructor with void return type as in the below example.
For example
class A
{
void A(){} //where A is constructor and for which return type is void
public static void main(string arg[]){
A a = new A();
}
}
A constructor does not have a result / return type.
If you add a result / return type to a "constructor" you turn it into a method whose name is the same as the class name. Then new won't be able to use it, and any this(...) or super(...) call in the method will be a syntax error.
For your example, you won't actually get an error. That is because Java will add a default no-args constructor for A ... because you haven't actually defined any constructors. The new in your example will actually be using the default constructor ....
If you changed your code to this:
class A {
void A() { System.err.println("hello"); }
public static void main(string arg[]) {
A a = new A();
}
}
and compiled and ran it, you should see that it DOES NOT give you any output. Remove the void and you will see output.
so here A() work as a method
It >>is<< a method. But it is not "working". As my version of your example shows ... the method is not being called at all.
You are confused why your code compiles. It's because A() is not actually a constructor but a method (that unfortunately has the same name as the class). The class A has an implicit default constructor which is used by main. The method A() is not used.
As others have pointed out, constructors do not have a return type.
Constructors don't have return type - https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Hope this example would be more easy to understand. In this example you can see Main as the class, constructor and method and how those works. Please see the output too.
See what happens when you call the constructor and what happens when the method called with constructor.
Program:
//Class
public class Main
{
//Constructor
public Main(){
System.out.println("Hello World 1");
}
//Method
public void Main(){
System.out.println("Hello World 2");
}
//Another method but static
public static void main(String[] args) { //This should be small letter 'main'
System.out.println("Hello World 3"); //Print this first
Main constructor = new Main(); //Run constructor and print.
constructor.Main(); //Run method (void Main()) and print.
}
}
Output:
Hello World 3
Hello World 1
Hello World 2
Note: Naming conventions not followed.

Static method override

class XYZ{
public static void show(){
System.out.println("inside XYZ");
}
}
public class StaticTest extends XYZ {
public static void show() {
System.out.println("inside statictest");
}
public static void main(String args[]){
StaticTest st =new StaticTest();
StaticTest.show();
}
}
though we know static methods cant be overridden. Then what actually is happening?
Static methods belong to the class. They can't be overridden. However, if a method of the same signature as a parent class static method is defined in a child class, it hides the parent class method. StaticTest.show() is hiding the XYZ.show() method and so StaticTest.show() is the method that gets executed in the main method in the code.
Its not overriding they are two different method in two different class with same signature. but method from XYZ isn't available in child class through inheritance .
It will call method from StaticTest
It's not overriden properly said... Static methods are 'tied' to the class so
StaticTest.show();
and
XYZ.show();
are two totally different things. Note you can't invoke super.show()
To see the difference you have to use more powerful example:
class Super {
public static void hidden(Super superObject) {
System.out.println("Super-hidden");
superObject.overriden();
}
public void overriden() {
System.out.println("Super-overriden");
}
}
class Sub extends Super {
public static void hidden(Super superObject) {
System.out.println("Sub-hidden");
superObject.overriden();
}
public void overriden() {
System.out.println("Sub-overriden");
}
}
public class Test {
public static void main(String[] args) {
Super superObject = new Sub();
superObject.hidden(superObject);
}
}
As Samit G. already have written static methods with same signature in both base and derived classes hide the implementation and this is no-overriding. You can play a bit with the example by changing the one or the another of the static methods to non-static or changing them both to non-static to see what are the compile-errors which the java compiler rises.
It's not an override, but a separate method that hides the method in XYZ.
So as I know, any static member (method or state) is an attribute of a class, and would not be associated with any instance of a class. So in your example, XYZ is a class, and so is StaticTest (as you know). So by calling the constructor two things first happen. An Object of type Class is created. It has a member on it call showed(). Class, XYZ.class, extends from Object so has all those Object methods on it plus show(). Same with the StaticClass, the class object has show() on it as well. They both extend java.lang.Object though. An instance of StaticClass would also be an instance of XYZ. However now the more interesting question would be what happens when you call show() on st?
StaticClass st = new StaticClass();
st.show();
XYZ xyz = st;
xyz.show();
What happens there? My guess is that it is StaticClass.show() the first time and XYZ.show() the second.
Static methods are tied to classes and not instances (objects).
Hence the invocations are always ClassName.staticMethod();
When such a case of same static method in a subclass appears, its called as refining (redefining) the static method and not overriding.
// Java allows a static method to be called from an Instance/Object reference
// which is not the case in other pure OOP languages like C# Dot net.
// which causes this confusion.
// Technically, A static method is always tied to a Class and not instance.
// In other words, the binding is at compile-time for static functions. - Early Binding
//
// eg.
class BaseClass
{
public static void f1()
{
System.out.println("BaseClass::f1()...");
} // End of f1().
}
public class SubClass extends BaseClass
{
public static void f1()
{
System.out.println("SubClass::f1()...");
// super.f1(); // non-static variable super cannot be referenced from a static context
} // End of f1().
public static void main(String[] args)
{
f1();
SubClass obj1 = new SubClass();
obj1.f1();
BaseClass b1 = obj1;
b1.f1();
} // End of main().
} // End of class.
// Output:
// SubClass::f1()...
// SubClass::f1()...
// BaseClass::f1()...
//
//
// So even though in this case, called with an instance b1 which is actually referring to
// an object of type SuperClass, it calls the BaseClass:f1 method.
//

Accessing constructor of an anonymous class

Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.
Object a = new Class1(){
void someNewMethod(){
}
};
Now is there any way I could overload the constructor of this anonymous class. Like shown below
Object a = new Class1(){
void someNewMethod(){
}
public XXXXXXXX(int a){
super();
System.out.println(a);
}
};
With something at xxxxxxxx to name the constructor?
From the Java Language Specification, section 15.9.5.1:
An anonymous class cannot have an
explicitly declared constructor.
Sorry :(
EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:
public class Test {
public static void main(String[] args) throws Exception {
final int fakeConstructorArg = 10;
Object a = new Object() {
{
System.out.println("arg = " + fakeConstructorArg);
}
};
}
}
It's grotty, but it might just help you. Alternatively, use a proper nested class :)
That is not possible, but you can add an anonymous initializer like this:
final int anInt = ...;
Object a = new Class1()
{
{
System.out.println(anInt);
}
void someNewMethod() {
}
};
Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.
Here's another way around the problem:
public class Test{
public static final void main(String...args){
new Thread(){
private String message = null;
Thread initialise(String message){
this.message = message;
return this;
}
public void run(){
System.out.println(message);
}
}.initialise(args[0]).start();
}
}
I know the thread is too old to post an answer. But still i think it is worth it.
Though you can't have an explicit constructor, if your intention is to call a, possibly protected, constructor of the super class, then the following is all you have to do.
StoredProcedure sp = new StoredProcedure(datasource, spName) {
{// init code if there are any}
};
This is an example of creating a StoredProcedure object in Spring by passing a DataSource and a String object.
So the Bottom line is, if you want to create an anonymous class and want to call the super class constructor then create the anonymous class with a signature matching the super class constructor.
Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse...
Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor
You can have a constructor in the abstract class that accepts the init parameters. The Java spec only specifies that the anonymous class, which is the offspring of the (optionally) abstract class or implementation of an interface, can not have a constructor by her own right.
The following is absolutely legal and possible:
static abstract class Q{
int z;
Q(int z){ this.z=z;}
void h(){
Q me = new Q(1) {
};
}
}
If you have the possibility to write the abstract class yourself, put such a constructor there and use fluent API where there is no better solution. You can this way override the constructor of your original class creating an named sibling class with a constructor with parameters and use that to instantiate your anonymous class.
If you dont need to pass arguments, then initializer code is enough, but if you need to pass arguments from a contrcutor there is a way to solve most of the cases:
Boolean var= new anonymousClass(){
private String myVar; //String for example
#Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);
Peter Norvig's The Java IAQ: Infrequently Answered Questions
http://norvig.com/java-iaq.html#constructors - Anonymous class contructors
http://norvig.com/java-iaq.html#init - Construtors and initialization
Summing, you can construct something like this..
public class ResultsBuilder {
Set<Result> errors;
Set<Result> warnings;
...
public Results<E> build() {
return new Results<E>() {
private Result[] errorsView;
private Result[] warningsView;
{
errorsView = ResultsBuilder.this.getErrors();
warningsView = ResultsBuilder.this.getWarnings();
}
public Result[] getErrors() {
return errorsView;
}
public Result[] getWarnings() {
return warningsView;
}
};
}
public Result[] getErrors() {
return !isEmpty(this.errors) ? errors.toArray(new Result[0]) : null;
}
public Result[] getWarnings() {
return !isEmpty(this.warnings) ? warnings.toArray(new Result[0]) : null;
}
}
It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.
Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.
In my case, a local class (with custom constructor) worked as an anonymous class:
Object a = getClass1(x);
public Class1 getClass1(int x) {
class Class2 implements Class1 {
void someNewMethod(){
}
public Class2(int a){
super();
System.out.println(a);
}
}
Class1 c = new Class2(x);
return c;
}

Categories

Resources