Java: How to create an object with and without parameters? [duplicate] - java

I'm new with Java and I'm having trouble understanding the constructor issue,
I have looked at many tutorials and still I'm having difficult to understand why we use constructors, anyway, my specific question is :
Correct me if I'm wrong, if i want to add in my class more than one constructor, I'll write the first one and the second will be int type (inside the brackets).
is it because the constructors have to be with the same name as the class and we need to distinguish between them ?
what if I want to add a third constructor ? Can it also be int type ?

a) is it because the constructors have to be with the same name as the
class and we need to distinguish between them ?
Yes constructors are always the name of the class without any return type, and in order to distinguish between them, you can have different parameters.
b) what if i want to add a third constructor ? it can be also int type
?
Yes, you can add any no. of overloaded constructors but those all should be different in no. and/or type of parameters.
Like :-
public User() // default constructor
{
}
public User(int age) // overloaded constructor with int
{
}
public User(String name) // // overloaded constructor with String
{
}
public User(String name, int age) // // overloaded constructor with String and int
{
}

Yes a constructor has the same name as the Class.
As long as the constructors have different signatures you can have as many as you want. The signature is what distinguishes one constructor from another...
public MyClass()
{
}
public MyClass(int a)
{
}
public MyClass(int a, int b)
{
}
public MyClass(String a)
{
}
public MyClass(int a, String b)
{
}
Those are all different because they have different signatures.

Actually, if you want to have 10000 constructor, you can as long a signature are differents.
public class People {
public People(String name, int age) {
...
}
public People(String name) {
...
}
}
You can construct your object in a different way.
You can see an example by yourself looking at : the java String class wich has a plenty of constructors.
And yes, all constructors have the same name of his class.
But this will not works :
public class People {
public People(String name, int age) {
...
}
public People(String name, int numberOfLegs) {
...
}
}
Since you have two constructors with the same signature

The constructors purpouse is to contain the code to inizialize the object. Usually, the initialization is done using constructor parameters. You can have different constructors with different parameters list, as needed by your context. It is a good pratice to do constructor chaining, that is calling a base constructor from others.

Adding to the #brso05 answer,
This is also one of the ways:
public MyClass( int a)
{
}
public MyClass( int a, int b)
{
}
public MyClass( int a, String b)
{
}
And So on..It is the arguments which make difference, rest remains the same!

Related

What is the class that declaring method of another class

I remember on my previous web development job that they have something like this:
sampleClassBean.java:
public class sampleClassBean
{
public String doSomeStrings(String a, String b){}
public Int doSomeInt(Integer i, integer j){}
public Boolean doSomeBoolean(Boolean result){}
}
and then there's sampleClassBeanImpl
public class sampleClassBeanImpl
{
public String doSomeStrings(String a, String b)
{
//do some process
return "";
}
public Integer doSomeInt(Integer i, Integer j)
{
//do some process
return 0;
}
public Boolean doSomeBoolean(Boolean result)
{
//do some process
return false;
}
}
For what I understand is that, there's 2 class, 1st class that declare methods, now 2nd class's methods will depend on what is declared on the 1st class. If the 2nd class create a method that is not declared in 1st class there will be an error. Hope you understand what i'm saying.
What I need to know is what exactly that? What do you call that process? How to do that? What are the benefits of doing that? Is it a good programming practice?
Yes it is good practice, you are talking about interfaces:
Java includes a concept called interfaces. A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.
The interface:
public interface SampleClassBean {
public String doSomeStrings(String a, String b);
public int doSomeInt(int i, int j);
public Boolean doSomeBoolean(Boolean result);
}
And the implementation:
public class SampleClassBeanImpl implements SampleClassBean {
#Override
public String doSomeStrings(String a, String b) {
return null;
}
#Override
public int doSomeInt(int i, int j) {
return 0;
}
#Override
public Boolean doSomeBoolean(Boolean result) {
return null;
}
}
Interfaces are really useful because unlike other languages Java doesn't support multiple inheritance but you can implement all the interfaces you wish!
Have a read of this it'll help you understand interfaces and when to implement them.

Confused by the compareTo answer

//The answer is 2 not sure why. Does it not invoke the object/class instance
//method if the method is overridden. Basically why is it invoking compareTo in the Person class instead of SoccerPlayer, why is the answer 2???? Thanks in advance
public class Person implements Comparable {
private String name;
public Person(String name) { this.name = name; }
public String getName() { return name; }
public boolean equals(Object other) {
return other != null && name.equals(((Person) other).name);
}
public int compareTo(Object other) {
return name.compareTo((Person other).name);
}
public int hashCode() { return name.hashCode(); }
}
public class SoccerPlayer extends Person {
private int numGoals;
public SoccerPlayer(String name, int n) {
super(name);
numGoals = n;
}
public int getNumGoals() { return numGoals; }
public void score() [ numGoals++; }
public int compareTo(SoccerPlayer other) {
return getNumGoals() - other.getNumGoals();
}
public String toString() {
return getName() + "/" + getNumGoals();
}
}
What is the result of the following code? //why 2???
Person players[] = { new SoccerPlayer("Mia Hamm", 7), new SoccerPlayer("Kristine Lilly", 6) };
System.out.println(players[0].compareTo((SoccerPlayer) players[1])); // Line ***
a. Syntax error in the class Person: other.name is not accessible
b. Syntax error in the class SoccerPlayer: compareTo is redefined
c. ClassCaseException on Line ***
d. Compiles with no errors, displays 1
e. Compiles with no errors, displays 2
There is no overriding here. One compareTo method takes an Object as argument, and the other takes a SoccerPlayer.
That's overloading, not overriding. Two methods with the same name, but not the same signature.
Since the declared type of the variable players[0] is Person, all the compiler knowns about this variable is that it's a Person, with a single compareTo method taking an Object as argument. So that method is the one being called.
Note that this code would have been fine a bit more than 10 years ago, when we were using Java 4, and generics didn't exist. Nowadays, using raw types is really bad practice. Person should implement Comparable<Person>, not Comparable.
Also note that the equals() implementation is wrong, too. It should return false rather than throw a ClassCastException if the object passed as argument is not a Person.

How to overload a GUI constructor? [duplicate]

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?
Yes, it is possible:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.
See also this related question, which is about C# but where the same principles apply.
Using this(args). The preferred pattern is to work from the smallest constructor to the largest.
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
You can also use a more recently advocated approach of valueOf or just "of":
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
To call a super class, use super(someValue). The call to super must be the first call in the constructor or you will get a compiler error.
[Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).]
In Java another constructor of the same class can be called from a constructor via this(). Note however that this has to be on the first line.
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, 0.0);
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
}
That this has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, getDefaultArg3(argument1, argument2));
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
private static double getDefaultArg3(double argument1, double argument2) {
double argument3 = 0;
// Calculate argument3 here if you like.
return argument3;
}
}
When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:
class MyClass {
int field;
MyClass() {
init(0);
}
MyClass(int value) {
if (value<0) {
init(0);
}
else {
init(value);
}
}
void init(int x) {
field = x;
}
}
But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example
class MyClass {
int field;
MyClass(int value) {
if (value<0)
field = 0;
else
field = value;
}
MyClass() {
this(0);
}
}
Within a constructor, you can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.
Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(1, 1);
}
public Rectangle(int width, int height) {
this( 0,0,width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.
As everybody already have said, you use this(…), which is called an explicit constructor invocation.
However, keep in mind that within such an explicit constructor invocation statement you may not refer to
any instance variables or
any instance methods or
any inner classes declared in this class or any superclass, or
this or
super.
As stated in JLS (§8.8.7.1).
Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.
Example:
Class Test {
Test() {
this(10); // calls the constructor with integer args, Test(int a)
}
Test(int a) {
this(10.5); // call the constructor with double arg, Test(double a)
}
Test(double a) {
System.out.println("I am a double arg constructor");
}
}
This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.
Using this keyword we can call one constructor in another constructor within same class.
Example :-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
Yes it is possible to call one constructor from another. But there is a rule to it. If a call is made from one constructor to another, then
that new constructor call must be the first statement in the current constructor
public class Product {
private int productId;
private String productName;
private double productPrice;
private String category;
public Product(int id, String name) {
this(id,name,1.0);
}
public Product(int id, String name, double price) {
this(id,name,price,"DEFAULT");
}
public Product(int id,String name,double price, String category){
this.productId=id;
this.productName=name;
this.productPrice=price;
this.category=category;
}
}
So, something like below will not work.
public Product(int id, String name, double price) {
System.out.println("Calling constructor with price");
this(id,name,price,"DEFAULT");
}
Also, in the case of inheritance, when sub-class's object is created, the super class constructor is first called.
public class SuperClass {
public SuperClass() {
System.out.println("Inside super class constructor");
}
}
public class SubClass extends SuperClass {
public SubClass () {
//Even if we do not add, Java adds the call to super class's constructor like
// super();
System.out.println("Inside sub class constructor");
}
}
Thus, in this case also another constructor call is first declared before any other statements.
I will tell you an easy way
There are two types of constructors:
Default constructor
Parameterized constructor
I will explain in one Example
class ConstructorDemo
{
ConstructorDemo()//Default Constructor
{
System.out.println("D.constructor ");
}
ConstructorDemo(int k)//Parameterized constructor
{
this();//-------------(1)
System.out.println("P.Constructor ="+k);
}
public static void main(String[] args)
{
//this(); error because "must be first statement in constructor
new ConstructorDemo();//-------(2)
ConstructorDemo g=new ConstructorDemo(3);---(3)
}
}
In the above example I showed 3 types of calling
this() call to this must be first statement in constructor
This is Name less Object. this automatically calls the default constructor.
3.This calls the Parameterized constructor.
Note:
this must be the first statement in the constructor.
You can a constructor from another constructor of same class by using "this" keyword.
Example -
class This1
{
This1()
{
this("Hello");
System.out.println("Default constructor..");
}
This1(int a)
{
this();
System.out.println("int as arg constructor..");
}
This1(String s)
{
System.out.println("string as arg constructor..");
}
public static void main(String args[])
{
new This1(100);
}
}
Output -
string as arg constructor..
Default constructor..
int as arg constructor..
Calling constructor from another constructor
class MyConstructorDemo extends ConstructorDemo
{
MyConstructorDemo()
{
this("calling another constructor");
}
MyConstructorDemo(String arg)
{
System.out.print("This is passed String by another constructor :"+arg);
}
}
Also you can call parent constructor by using super() call
There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.
With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.
class LambdaInitedClass {
public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
init.accept(this);
}
}
Call it with...
new LambdaInitedClass(l -> { // init l any way you want });
Pretty simple
public class SomeClass{
private int number;
private String someString;
public SomeClass(){
number = 0;
someString = new String();
}
public SomeClass(int number){
this(); //set the class to 0
this.setNumber(number);
}
public SomeClass(int number, String someString){
this(number); //call public SomeClass( int number )
this.setString(someString);
}
public void setNumber(int number){
this.number = number;
}
public void setString(String someString){
this.someString = someString;
}
//.... add some accessors
}
now here is some small extra credit:
public SomeOtherClass extends SomeClass {
public SomeOtherClass(int number, String someString){
super(number, someString); //calls public SomeClass(int number, String someString)
}
//.... Some other code.
}
Hope this helps.
Yes it is possible to call one constructor from another with use of this()
class Example{
private int a = 1;
Example(){
this(5); //here another constructor called based on constructor argument
System.out.println("number a is "+a);
}
Example(int b){
System.out.println("number b is "+b);
}
You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword
(when you need to call a constructor from a superclass).
However, such a call must be the first statement of your constructor. To overcome this limitation, use this answer.
The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.
Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.
Setter methods or constructors
I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String args[])
{
Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
Dog cs = new Dog("Bite"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
// You need to Explicitly tell the java compiler to use Argument constructor so you need to use "super" key word
System.out.println("------------------------------");
Cat c = new Cat();
Cat caty = new Cat("10");
System.out.println("------------------------------");
// Self s = new Self();
Self ss = new Self("self");
}
}
class Animal
{
String i;
public Animal()
{
i = "10";
System.out.println("Animal Constructor :" +i);
}
public Animal(String h)
{
i = "20";
System.out.println("Animal Constructor Habit :"+ i);
}
}
class Dog extends Animal
{
public Dog()
{
System.out.println("Dog Constructor");
}
public Dog(String h)
{
System.out.println("Dog Constructor with habit");
}
}
class Cat extends Animal
{
public Cat()
{
System.out.println("Cat Constructor");
}
public Cat(String i)
{
super(i); // Calling Super Class Paremetrize Constructor.
System.out.println("Cat Constructor with habit");
}
}
class Self
{
public Self()
{
System.out.println("Self Constructor");
}
public Self(String h)
{
this(); // Explicitly calling 0 args constructor.
System.out.println("Slef Constructor with value");
}
}
It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:
public Omar(){};
public Omar(a){};
public Omar(a,b){};
public Omar(a,b,c){};
public Omar(a,b,c,d){};
...
You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful
https://medium.com/#modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e
Yes, you can call constructors from another constructor. For example:
public class Animal {
private int animalType;
public Animal() {
this(1); //here this(1) internally make call to Animal(1);
}
public Animal(int animalType) {
this.animalType = animalType;
}
}
you can also read in details from
Constructor Chaining in Java
Originally from an anser by Mirko Klemm, slightly modified to address the question:
Just for completeness: There is also the Instance initialization block that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.
So in your case
{
System.out.println("this is shared constructor code executed before the constructor");
field1 = 3;
}
There is also a "static" version of this to initialize static members: "static { ... }"
I prefer this way:
class User {
private long id;
private String username;
private int imageRes;
public User() {
init(defaultID,defaultUsername,defaultRes);
}
public User(String username) {
init(defaultID,username, defaultRes());
}
public User(String username, int imageRes) {
init(defaultID,username, imageRes);
}
public User(long id, String username, int imageRes) {
init(id,username, imageRes);
}
private void init(long id, String username, int imageRes) {
this.id=id;
this.username = username;
this.imageRes = imageRes;
}
}

Multiple parameters for a single method

I don't know how simple this would be or if it is possible but I can't seem to find any information on it. For a method is there a way to set multiple parameters.
For example in this public void it is required you call a component and and string when you call the method in your java file.
public void testMethod(Component c, String s)
{
//Do Something
}
Is there way to say public void testMethod(Component c, String d) or public void testMethod(Component c, int i) and when the method is called either could be specified?
It's called method overloading. Just create them as separate methods and the compiler will (usually) infer the right one based on your input values.
Yes this is possible and is an inportant concept. This particular technique is called function overloading. Suppose you declare 2 functions like:
public void testMethod(Component c, String d) {} //function 1
and
public void testMethod(Component c, int d) {} //function 2
You can then call these functions from main as:
testMethod(c,"Hello") //calls function 1
testMethod(c,1) //calls function 2
It is called "method overloading". Any two methods can have the same name, as long as the parameters are different. For example:
public void doStuff(String string, int integer) {}
public void doStuff(Object object, float flt) {}
This also applies for constructors:
public Thing(String name, int id) {}
public Thing(Object object, long id) {}
However, take the following two methods for example:
public void doStuff(String string) {}
public void doStuff(Object object) {}
Now, call the method doStuff(null). The compiler cannot infer which one to use; in which case, you will get a compilation error. This also occurs in constructors (just to get it out of the way, constructors are almost the same as methods).
Simply stated, you can.
public void testFunction(Component c, String s) {
// Handle on a string
}
public void testFunction(Component c, int i) {
// Handle on integer
}
This is called method overloading. Whichever type is passed will cause your function call to use the appropriate method. The order of the parameters is still important.

Real life scenarios for calling a constructor from another constructor

I know it is possible to call one constructor from another constructor via the use of "this".
But I would like to know is, why do we do it (i.e calling a constructor from another constructor)
Can anyone relate a simple example of where this might be actually useful ?
ArrayList is a nice example. The default constructor calls the constructor that takes the initial capacity of the underlying array. This looks like this:
public ArrayList()
{
this(10);
}
public ArrayList(int capacity)
{
objects = new Object[capacity];
}
If we do not want to duplicate code:
class Foo{
int requiredParam;
String name;
double optionalPrice;
Object extraObject;
public Foo(int rp, String name){
this.requiredParam=rp;
this.name=name
}
public Foo(int rp, String name, double op, Object e){
this(rp, name);
this.optionalPrice=op;
this.extraObject=e;
}
How about a simple class like this:
class Person {
String name;
Person(String firstName, String lastName) {
this(firstName + lastName);
}
Person(String fullName) {
name = fullName;
}
}
Different constructors give you the freedom of creating similar objects in different flavors.

Categories