WHAT IS A CONSTRUCTOR
"It is a special type of method same name as class name that determines how an object is initialized when it's created".
what is constructor in java
Like other methods, we can also define constructor Method in our java program but unlike other methods, we cannot call a constructor directly; Java called constructor automatically when an object has created. When we use new keyword to create an object of a class, java does three thing;
Allocates memory for the object.
Initialize that object instance variable, with their initial value or to a default.
Call the constructor Method of the class.
If a class doesn't have defined any constructor method, we will still create an object of that class but we have to set instance variable or call other methods that object needs to initialize itself to that object afterward.
By defining constructor method in our own classes, we can set initial values of instance variable, call method based on those variable or call methods on other objects, or calculate initial properties of our object. We can also overload constructor, as we would regular methods, to create an object that has specific properties based on the argument we give to new.
BASIC CONSTRUCTOR
by defining a constructor looks like a regular method, with 2 basic difference.
Constructor and class name are always same.
It doesn't have any return type
For example, in the below table a simple class person, with a constructor that initializes it's instance variable based on the argument to new. The class also includes a method for the object to introduce itself, and a main() method to test each of these class.
class Person
{
String name;
int age;
Person (String n, int a)
{
name = n;
age = a;
}
void printPerson ()
{
System.out.print("Hi, I am " +name);
System.out.println(" I am "+ age + " years old.");
}
public static void main(String args[])
{
Person p;
p = new Person ("Ajab", 20);
p.printPerson();
p = new Person ("Rizwan", 30);
p.printPerson();
The output of the program is given below:
Hi, I am Ajab. I am 20 years old.
Hi, I am Rizwan. I am 30 years old
CONSTRUCTOR OVERLOADING
like other methods, constructor can also take different number and types of parameters, enabling us to create our objects with exactly the properties you want it to have, or for it to be able to calculate properties from different kinds of input.
constructor overloading in Java
For example, the MyRectone class in the given table creates a MyRectone Constructor and passing different parameter instead of creating different methods for the given arguments.
class MyRectone
{
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
MyRectone ( int x1, int x2, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
MyRectone (Point topLeft, Point bottomRight)
{
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
}
MyRectone ( Point topLeft, int w, int h)
{
x1 = topLeft.x;
y1 = top left.y;
x2 = ( x1 + w);
y2 = (y1 + h);
}
void printRect ()
{
System.out.print ("MyRectone: ");
}
public static void main (String args [] )
{
MyRectone rect;
System.out.println ("Calling MyRectone with coordinates 35,35 70,70");
rect = new MyRectone (35,35,70,70);
rect.printRect();
System.out.println ("Calling MyRectone with coordinates (15,15) (30,30)");
rect = new MyRectone (15,15,30,30);
rect.printRect();
System.out.print (" Calling buildRect w/1 point (10,10),");
System.out.println ("width (50) and height (50)");
rect = new MyRectone ( new Point (10,10), 50, 50);
rect.printRect();
Output
Calling MyRectone with coordinates 35,35 70,70:
MyRectone:
Calling buildRect w/1 points (15,15), (30,30):
MyRectone:
Calling buildRect w/1 point (10,10), width (50) and height (50):
MyRectone:
CALLING ANOTHER CONSTRUCTOR
Some constructor may be a superset of another constructor defined in your class; that is, they might have the same behavior plus a little bit more. Rather than duplicating identical behavior in multiple constructor Methods in our class, it makes sense to be able to just call that first constructor from inside the body of the second constructor. Java provides a special syntax for doing this. To call a constructor defined on the current class, use this form:
this (arg1, arg2, arg3 …..);
The arguments to this are, of course, the arguments to the constructor.
What is meant by instancing a class?
The class can be considered a template to create objects. When you create an object, you create it on the basis of the specified class - the object is an instance of the class, and the act of creating the object is also known as "instantiating" the class.
Write a program in java to find gcf of two numbers?
There are two basic steps to finding the greatest number. 1) convert the input from Strings to ints (or doubles or whatever number type you are expecting), 2) find the greatest number.
/*
For this example we're going to answer the question exactly,
with no regard to expandability (for dealing with more numbers).
*/
public static void main(String[] args) {
// step 1 - convert input from Strings to ints
int a = 0, b = 0, c = 0;
// we need to wrap a try-catch block around this to
// deal with any input that cannot be converted from
// a String to an int
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = Integer.parseInt(args[2]);
}catch(NumberFormatException ex) {
// do whatever you need to do here to manage the
// exception
}
// step 2 - find the greatest number
int max = a;
if(b > max) {
max = b;
}
if(c > max) {
max = c;
}
// at this point the value in max is the greatest of the three
// numbers passed in through the command line
}
OR ELSE YOU SHOULD TRY THE ANOTHER STYLE FOR COMMAND LINE ARGUMENT , AS IT IS GIVEN BELOW.
class Max_command
{
public static void main(String args[])
{
for(String name : args)
{
System.out.println(name);
}
int i,max=0;
for(i=0;i<=args.length;i++)
{
int a=Integer.parseInt(args[i]);
if(a>max)
{
max=a;
}
if(i==args.length-1)
{
System.out.println("Max is --> "+max);
}
}
}
}
Why the concept of inheritance was introduced in OOP?
In object-oriented programming, inheritance allows the creation of is-a relationships. For example, a car is a vehicle, and a bike is a vehicle, so those could be modeled through a vehicle class, and a pair of car and bike classes, both derived from (inheriting from) the vehicle class. Derived classes like car and bike share common vehicle properties, such as speed, location, direction, number of wheels, etc.
How do you avoid repeating code in Java?
By using Inheritance. By using Inheritance once class can re-use or inherit the features of another class.
Ex:
public class Ferrari extends Car {
...
}
Here, the class Ferrari reuses code/features of the class Car.
Why you use constructor chaining?
Constructor Chaining
We know that constructors are invoked at runtime when you say new on some class type as follows:
Lamborghini h = new Lamborghini();
But what really happens when you say new Lamborghini() ? (Assume Lamborghini extends Car and Car extends Object.)
1. Lamborghini constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(),
2. Car constructor is invoked (Car is the superclass of Lamborghini).
3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Car extends Object even though you don't actually type "extends Object" into the Car class declaration. It's implicit.) At this point we're on the top of the hierarchy.
4. Object instance variables are given their explicit values. By explicit values, we mean values that are assigned at the time the variables are declared, like "int x = 27", where "27" is the explicit value (as opposed to the default value) of the instance variable.
5. Object constructor completes.
6. Car instance variables are given their explicit values (if any).
7. Car constructor completes.
8. Lamborghini instance variables are given their explicit values (if any).
9. Lamborghini constructor completes.
A public class is a base class declared with public inheritance:
class base {
// ...
};
class derived : public base {
// ...
};
In the above example, base is a public class of derived, thus derived is regarded as being a type of base. The derived class inherits all the public and protected methods of its base. Protected methods are accessible to the derived class, its derivatives and their friends.
If base were declared protected, its public methods become protected methods of derived. The base class is then an implementation detail of derived; only members of derived, its derivatives and their friends can treat derived as being a type of base.
If declared private, the public and protected methods of base become private methods of derived. The base class is then an implementation detail of derived; only members of derived and its friends can treat derived as a type of base.
Write a C programme to find out sum of the array elements?
main()
{
int n,a[i],s;
s=0;
printf("enter no of elements in array");
scanf("%d",&n);
printf("Enter elements in array");
for(i=;i
scanf("%d",&a[i]);
s+=a[i];
}
printf("sum of elements=%d",s);
return;
}
Which data type stores only one of two values?
In Java, such a data type is called boolean. In other programming languages it may be known by different names, including variations of "boolean" such as "bool", and "logical".
Is Java always provides a default constructor to a class?
Correct. If you omit a constructor, Java will assume that an empty one exists.
Given the following code for a class:
class MyClass {
}
You can make a call to the default constructor:
MyClass mc = new MyClass();
Just keep in mind that the default constructor "goes away" if you implement another constructor.
class MyClass {
public MyClass(String str){
}
}
This line will now result in a "cannot find symbol" compiler error:
MyClass mc = new MyClass();
Any device or construct that allows a human being to interact with a machine is an interface. The steering wheel of a car is an interface, the play button on a DVD video player is an interface, the close icon on a window is an interface, the CTRL+C accelerator is an interface, and so on.
How do you compile program in java in scite editor?
These directions were written with the assumption you are using TextPad 5:
First, you must download and install the JDK - probably the most recent one. You can download this at: http://java.sun.com/javase/downloads/?intcmp=1281
After you have successfully installed the JDK, in TextPad click on the Configure menu, and then Preferences.
From the preferences screen, click on the 'Tools' heading on the left.
In the tools section, click on the 'Add' button on the right, then on the 'Java SDK Commands' option, and finally on Ok.
Once you've done this, you are ready to compile and run java programs. To do this, once you've opened a .java file, click on tools, external tools, and compile java.
In order to run the application after you compile it, just go to tools, external tools, and run java application (or run java applet if it's an applet).
Why you use overloading and overriding?
Overloading the same method name with different number of arguments (and the data types), and perhaps with a different returned data type. The method signatures are different, only the names are the same.
Overriding is to change the same method name with different implementation (the method body). The method signature stays the same.
How you can create an object of a class in java?
for creating objects use the new operator along with a call to the constructor. for ex Triangle t = new Triangle(); In this statement the new operator creates a triangle object and the constructor is called which initializes the object and then new returns a reference of the object which is stored in the reference var "t" of type Triangle.
Is it possible to declare class as private?
Yes, but not in a normal way.
Sample code:
namespace WikiAnswers {
public class MainClass {
protected class HereItIs {}
}
}
The inner class MainClass.HereItIs is the answer to this question.
If you change the accessibility of MainClass from public to protected, the compilation will fail.
My interpretation of the keyword protected is: "accessible to the class itself and its derived classes", and may only decorate/mark it to class elements (data members, methods, properties, etc.)
Noramlly, we declare a class as a namespace element, e.g. MainClass above, I almost answered 'NO' to this question when I read the question the first time. Tricky.
The above example may be applicable to Java:
1. replace namespace to package
2. the rest of the codes should be the same
What are the benefit of using package in java?
Packages provide an alternative to creating procedures and functions as stand-alone schema objects, and they offer the following advantages:
Write a program to print even and prime numbers from 100 to 200 in core java language?
I could write the program quickly, but I want to leave you part of the fun.
Just write a loop for the numbers from 2-100 (1 is not considered a prime number). Write a second loop to test divisibility of each number, "n", with all factors lower than that number (from 2 to n-1). If such a factor exists, the number is NOT a prime number.
To test for divisibility, use the remainder of a division.
if (n % factor == 0)
// If true, it is divisible.
What are merit and demerit of polymorphism in oops?
Assuming the code is well written:
Pros:
* Easier to re-use * Easier to read and understand * More logical structure Cons:
* Less efficient * Has higher ram usage * Requires more data protection Of course badly written OOP can have none of these advantages, while very well written procedural code can offer the same advantages with minimal disadvantages. This is all in general though.
Rosen method movement (an adjunct to Rosen method bodywork) consists of simple fun movement exercises done to music in a group setting.
A loop control variable that is incremented a specific number of times is known as?
A loop control variable is widly known as a "counter".
What are the Advantages of linked list over stack and queue?
A linked list is a data structure in which each node has a pointer to the next node, and thus the whole list is linked.
Some advantages are:
* Easy traversal of the whole list (simply follow the pointers) * Easy insertion and deletion of nodes (don't need to move all the other nodes around)
Can arrays be created dynamically?
Yes, arrays can be created dynamically. The following shows how it can be done in C:
void f (unsigned n) {
int* p = malloc (n * sizeof (int)); /* allocate memory to accommodate n integers */
/* use p... */
free (p);
p = 0;
}
What is meant by inheritance and types of inheritance?
In advanced programming languages, the re-usability of a portion of code capable of performing a given function is an unique advantage. The compartmentalization of a code which can be reused later and invoked by the class name is referred as object inheritance. In classical inheritance classes are used while in object inheritance sub classes and super classes are add-on features. It saves lengthy redundant coding by inherting the desired code function and calling it by name .
-JP Morgan
What is difference in use between interfaces and abstract classes in java?
While neither abstract classes nor interfaces can be instantiated in Java, you can implement methods in abstract classes. Interfaces can only define methods; no code beyond a method header is allowed.
Actually, java does not support multiple inheritance. You can achieve partial multiple inheritance using interfaces but java is not like C or C++ where you can do direct multiple inheritance. However, you can achieve partial multiple inheritance with the help of interfaces.
Ex: public class FerrariF12011 extends Ferrari implements Car, Automobile {