Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor:
Constructor name must be same as its class name.
Constructor must not have any explicit return type.
Constructrs can not be abstract, static, final or synchronized.
Example:
class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Two types of Constructor:
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Two types of Constructor:
1.Default constructor
(no-arg constructor) : Default constructor provides the default values to the object like 0, null etc.
2.Parameterized constructor
Default constructor provides the default values to the object like 0, null etc.
Each time a new object is created at least one constructor will be invoked.
Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked
NOTE : If there is no constructor in a class, compiler automatically creates a default constructor.
Car c = new Car(name); //Parameterized constructor invoked
NOTE : If there is no constructor in a class, compiler automatically creates a default constructor.
Constructors Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters.
Why do we Overload constructors ?
Constuctor overloading is done to construct object in different ways.
Example:
class Cricketer
{
String name;
String team;
int age;
Cricketer () //default constructor.
{
name ="";
team ="";
age = 0;
}
Cricketer(String n, String t, int a) //constructor overloaded
{
name = n;
team = t;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++
{
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString()
{
return "This is " + name + " of "+team;
}
}
{
String name;
String team;
int age;
Cricketer () //default constructor.
{
name ="";
team ="";
age = 0;
}
Cricketer(String n, String t, int a) //constructor overloaded
{
name = n;
team = t;
age = a;
}
Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++
{
name = ckt.name;
team = ckt.team;
age = ckt.age;
}
public String toString()
{
return "This is " + name + " of "+team;
}
}
public class test
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("Sachin", "India", 43);
Cricketer c3 = new Cricketer(c2 );
{
public static void main (String[] args)
{
Cricketer c1 = new Cricketer();
Cricketer c2 = new Cricketer("Sachin", "India", 43);
Cricketer c3 = new Cricketer(c2 );
c1.name = "Virat";
c1.team= "India";
c1.age = 27;
c1.team= "India";
c1.age = 27;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
}
}
Output:
This is Virat of India
This is Sachin of India
This is Sachin of India
System.out.println(c2);
System.out.println(c3);
}
}
Output:
This is Virat of India
This is Sachin of India
This is Sachin of India
Difference between constructor and method in java
Constructor Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
Object is a physical entity. Class is a logical entity.
Constructor is invoked implicitly. Method is invoked explicitly.
Object is created many times as per requirement. Class is declared once.
The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
Object is a physical entity. Class is a logical entity.
Constructor is invoked implicitly. Method is invoked explicitly.
Object is created many times as per requirement. Class is declared once.
The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.
Q. What is constructor chaining in Java??
NOTE : Constructor chaining is a phenomena of calling one constructor from another constructor of same class. Since constructor can only be called from another constructor in Java, constructor chaining is used for this purpose.
class Test
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
}
Output:
x=10
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
}
Output:
x=10
Q. Does constructor return any value??
Ans:Yes, Constructor return current class instance (You cannot use return type yet it returns a value).
this keyword is used to refer current class object.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method(implicitly).
this can be passed as an argument in the method or constructor call.
this keyword can also be used to return the current class instance.
Example:
class Box
{
Double width, weight, dept;
Box (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
}
Here the this is used to initialize member of current object.
{
Double width, weight, dept;
Box (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
}
Here the this is used to initialize member of current object.
NOTE : Call to this() must be the first statement in constructor.
this is used to call overloaded constructor (or constructor chaining) in java.
class Car
{
private String name;
public Car()
{
this("BMW"); //oveloaded constructor is called.
}
public Car(Stting n)
{
this.name=n; //member is initialized using this.
}
}
this is also used to call Method of that class.
{
private String name;
public Car()
{
this("BMW"); //oveloaded constructor is called.
}
public Car(Stting n)
{
this.name=n; //member is initialized using this.
}
}
this is also used to call Method of that class.
public void getName()
{
System.out.println("BeTheDeveloper");
}
{
System.out.println("BeTheDeveloper");
}
public void display()
{
this.getName();
System.out.println();
}
this is used to return current Object.
{
this.getName();
System.out.println();
}
this is used to return current Object.
public Car getCar()
{
return this;
}
{
return this;
}
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
variable (also known as class variable).
method (also known as class method).
block.
nested class.
static variable
If you declare any variable as static, it is known static variable.
1. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
2. The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
NOTE : Java static property is shared to all objects.
Example: Program of counter by static variable.
class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
2
3
Static variable vs Instance Variable
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:
1
2
3
Static variable vs Instance Variable
Static variable Instance Variable
Represent common property. Instance Variable.
Accessed using class name. Accessed using object.
get memory only once. get new memory each time a new object is created.
Represent common property. Instance Variable.
Accessed using class name. Accessed using object.
get memory only once. get new memory each time a new object is created.
Static Method
If you apply static keyword with any method, it is known as static method.
1. A static method belongs to the class rather than object of a class.
2. A static method can be invoked without the need for creating an instance of a class (or objects).
3. static method can access static data member and can change the value of it.
Example: Program to get cube of a given number by static method.
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output: 125
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output: 125
Restrictions for static method
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A{
int a=40; //non static
public static void main(String args[]){
System.out.println(a);
}
}
Output: Compile Time Error
Q. Why java main method is static??
int a=40; //non static
public static void main(String args[]){
System.out.println(a);
}
}
Output: Compile Time Error
Q. Why java main method is static??
Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
static Block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
It is executed before main method at the time of classloading.
Example of static block
class S2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("main method is invoked");
}
}
Output:
static block is invoked
main method is invoked
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("main method is invoked");
}
}
Output:
static block is invoked
main method is invoked
Cool keep it up..
ReplyDeleteThanks
DeleteThe construction industry is on a boom and that has brought with it a number of advantages. Unemployment and underemployment are problems that wreck every economy. آرین سازه
ReplyDeleteIt is very much important to repair your car when it gets damaged or it goes out of order. So auto repair becomes essential when your vehicle gets damaged and cannot work properly. PTFE Hose
ReplyDeleteAs technology advances and new business models evolve, the real estate industry has begun to transform itself from providing traditional, carefully controlled "agent-centric" transactions to new "consumer-centric" practices. This article examines some of the recent industry trends and how buyers, sellers and investors can expect to benefit. The "Five Ds" that are driving change in real estate are: 1. Disruption 2. Displacement 3. Demanding consumers 4. Downward pressure on commissions 5. Developing alternatives andrew leavitt las vegas
ReplyDeleteThe construction industry is on a boom and that has brought with it a number of advantages. Unemployment and underemployment are problems that wreck every economy. رحلة كروز السعودية
ReplyDeleteMaintaining a รับทาสีอาคาร or building can be a daunting task especially if you don't know what to do and where to start. At some point, you can start with the restoration or renovation areas, such as putting up a new paint for the wall.
ReplyDeleteIt’s the pity you actually don’t possess a donate switch! I’d most likely donate to this superior site! We suppose that for now i’ll are satisfied with book-marking as well as adding your own Rss feed in order to my personal Search engines accounts. We appear forth in order to recent posts and can show this particular web page along with my personal Myspace group: ) buy steroids online
ReplyDeleteA dream bedroom starts with a dream bed right? Well if you can't afford a brand new bed and need a change, you might want to consider buying a mattress pad or cover at a mattress sale. This can be a great alternative for those homeowners who are budget conscious. Best mattresses
ReplyDeleteAt any construction site, one of the most important things that need to be ensured is safety of the people working there and for this construction site safety, training is very important. Having the best safety controls in place at the construction site is pointless, if workers aren't aware of the hazards that work in the building industry can present. Towing Company Lake Charles LA
ReplyDeleteIt looks awful when you are having a well furnished home but still are suffering with the tap water leaks and jammed plumbing systems. Every problem has its solution including yours. Georgia Plumbers provide you with all the plumbing related issues. plumbers west monroe la
ReplyDeleteWant to explore a career that can succeed even in hard economic times? Why not take a look at training to become a plumbing professional? emergency plumber new orleans
ReplyDeleteAccounting jobs in the construction industry are slightly hard to identify right away. However, if you are good with accounts and want to pursue a career in the construction industry, fret not for we are surely going to bail you out of the situation. http://newcaneyasphaltpros.com/
ReplyDeleteThe complex art of plumbing necessitates expert and professional hands if done correctly. From aligning the plumbing patterns to the Government guidelines to making room for improvisations, professional consultations is a must before indulging in any sort of plumbing activities. plumbers bountiful utah
ReplyDeleteA plumbing system usually refers to a network of pipes and fixtures which regulate the potable water and the waste in a building. The construction of plumbing structures varies from town to town depending on the weather and overall public infrastructure. Areas with extremely low temperature need a plumbing system which can handle the harsh weather and ensure uninterrupted supply of clean water and quick waste removal. plumber riverton ut
ReplyDeleteObtaining a plumbing service contractor may be simple, but hiring a plumbing specialist is not really an easy thing to do. To prevent yourself from making the most common errors of picking a poor plumbing service company, you might want to take into consideration a few things. plumber west jordan utah
ReplyDeleteIf you have any desire to move beyond goldfish and guppies and into the exciting world of saltwater reef aquariums, you are going to have to tackle the basics of plumbing your aquarium. Many of the invertebrates you work with in a reef aquarium require a strong flow of water running constantly through the setup. This water movement is critical for the exchange of oxygen and carbon dioxide, as well as removing waste products produced by live coral and other creatures you may have in your aquarium. Plumbers in Sandy Utah
ReplyDeleteA lot of individuals are of the view that carrying out a plumbing job can be easy and hassle-free. However, they are not aware that this is type of work is something that only professionals and experts can properly execute. Many people try to do a plumbing job at home on their own, from water pipes that have leaked or sinks and bowls that have clogged. Your father or mother may have done this to save from plumbing job expenses, but know that nothing a plumbing problem is always solved best by a professional plumber. plumbers in park city utah
ReplyDeleteA plumbing system usually refers to a network of pipes and fixtures which regulate the potable water and the waste in a building. The construction of plumbing structures varies from town to town depending on the weather and overall public infrastructure. Areas with extremely low temperature need a plumbing system which can handle the harsh weather and ensure uninterrupted supply of clean water and quick waste removal. Plumbing Maintenance
ReplyDeleteThe construction industry is on a boom and that has brought with it a number of advantages. Unemployment and underemployment are problems that wreck every economy. concrete patio houston
ReplyDeleteConstruction safety is a big deal. Construction on its own is somewhat of an inherently dangerous trade. Construction workers are in environments with lots of people and equipment, and the chances of injury are higher on a construction site than those at the average cubicle- filled office. kitchen remodeling
ReplyDeleteLocal Landscaping Cranbourne is your premium local landscaping service in Cranbourne and the surrounding area. Our services include Landscape and Garden Design, Landscape Construction, Landscape Water Features, Landscape Lighting Installation, Landscape Maintenance Service, Gardening Service, Lawn Care Installation and Maintenance Services, including the area around your driveway. No job is too big or too small for your Cranbourne landscaping requirements. Call Local Landscaping Cranbourne today to discuss your requirements on (03) 5910 3000 Cranbourne Landscaping
ReplyDeleteIt is a common fact that we find a wide variety of construction machines on every construction sites, which make the construction jobs easy, safe and quicker. Depending on the application, construction machines are classified into various categories which we are discussing here. Diesel Truck Repair Diesel Mechanic Diesel Mechanic Truck Repair
ReplyDeleteThe construction industry is on a boom and that has brought with it a number of advantages. Unemployment and underemployment are problems that wreck every economy. lakewood ranch homes for sale
ReplyDeleteAccounting jobs in the construction industry are slightly hard to identify right away. However, if you are good with accounts and want to pursue a career in the construction industry, fret not for we are surely going to bail you out of the situation. ann arbor deck
ReplyDeleteConstruction in Kansas has achieved a lot of growth owing to the economic development of the state. This however does not mean that there are plentiful jobs in the state. ann arbor handyman
ReplyDeleteOpen Wall construction is not limited to a single technique. The theories and principles behind the construction are unique, but the design uses existing methods and materials to allow for complete flexibility. handyman services ann arbor
ReplyDeleteOpen Wall construction is not limited to a single technique. The theories and principles behind the construction are unique, but the design uses existing methods and materials to allow for complete flexibility. swimming pool repair tucson
ReplyDeleteThe article discusses how detailed and unambiguous retail construction drawing sets can help moderate-budget retail projects, which use design-bid-build delivery methods, to avoid change orders and increase project profitability. Also highlighted is the key role that such retail construction drawing sets play in helping all the parties involved, including the architects, designers, and contractors. homes for sale arlington ridge leesburg fl
ReplyDeletePlanning to sell a home in Miami real estate requires time, effort and preparation. It is not just purely putting a for sale sign outside your home. monstera deliciosa
ReplyDeletePlumbing fittings include a wide assortment of plumbing hardware including pipes, faucets and the joints that connect these fixtures. It is important to install quality plumbing fittings in order to have an uninterrupted water supply and properly functioning drainage system. Landscaping Cranbourne
ReplyDeleteAt any construction site, one of the most important things that need to be ensured is safety of the people working there and for this construction site safety, training is very important. Having the best safety controls in place at the construction site is pointless, if workers aren't aware of the hazards that work in the building industry can present. Wrecker Service
ReplyDeleteThough there are many other professionals involved in a building construction project, it is the construction manager who takes the full responsibility of the project. In order to be in such a position they are well educated and trained. They coordinate the work of all other professionals in order to obtain the best results. Wrecker Service
ReplyDelete