Professional Documents
Culture Documents
OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a
collection of objects. Each object is nothing but an instance of a class.
2. Write basic concepts of OOPS?
Following are the concepts of OOPS and are as follows:.
1. Abstraction.
2. Encapsulation.
3. Inheritance.
4. Polymorphism.
3. What is a class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the
details of an object.
4. What is an object?
Object is termed as an instance of a class, and it has its own state, behavior and identity.
5. What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can
be restricted to the members of that class.
Levels are Public,Protected, Private, Internal and Protected Internal.
6. What is Polymorphism?
Polymorphism is nothing butassigning behavior or value in a subclass to something that was already
declared in the main class. Simply, polymorphism takes more than one form.
7. What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another class.
Ifinheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it
is called multiple Inheritance.
8. What are manipulators?
Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>)
operators on an object. Examples are endl and setw.
9. Define a constructor?
Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object
creation. Rules forconstructor are:.
Operator overloading is a function where different operators are applied and depends on the arguments.
Operator,-,* can be used to pass through the function , and it has their own precedence to execute.
Example:
C#
1 class complex {
2 double real,
3 imag; public: complex(double r, double i) : real(r),
4 imag(i) {} complex operator+(complex a, complex b);
5 complex operator*(complex a, complex b);
6 complex& operator=(complex a, complex b);
7}
a=1.2, b=6
16. What is an abstract class?
An abstract class is a class which cannot be instantiated. Creation of an object is not possible with
abstract class , but it can be inherited. An abstract class can contain only Abstract method. Java allows
only abstract method in abstract class while for other language it allows non-abstract method as well.
17. What is a ternary operator?
Ternary operator is said to be an operator which takes three arguments. Arguments and results are of
different data types , and it is depends on the function. Ternary operator is also called asconditional
operator.
18. What is the use of finalize method?
Finalize method helps to perform cleanup operations on the resources which are not currently used.
Finalize method is protected , and it is accessible only through this class or by a derived class.
19. What are different types of arguments?
A parameter is a variable used during the declaration of the function or subroutine and arguments are
passed to the function , and it should match with the parameter defined. There are two types of
Arguments.
Call by Value Value passed will get modified only inside the function , and it returns the same value
Call by Reference Value passed will get modified in both inside and outside the functions and it returns the
Private.
Protected.
Public.
Friend.
Protected Friend.
30. How can we call the base method without creating an instance?
Yes, it is possible to call the base method without creating an instance. And that method should be,.
Static method.
Doing inheritance from that class.-Use Base Keyword from derived class.
31. What is the difference between new and override?
The new modifier instructs the compiler to use the new implementation instead of the base class function.
Whereas, Override modifier helps to override the base class function.
32. What are the various types of constructors?
There are three various types of constructors , and they are as follows:.
Default Constructor With no parameters.
Parametric Constructor With Parameters. Create a new instance of a class and also passing
arguments simultaneously.
Copy Constructor Which creates a new object as a copy of an existing object.
33. What is early and late binding?
Early binding refers to assignment of values to variables during design time whereas late binding refers to
assignment of values to variables during run time.
34. What is this pointer?
THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates
between the current object with the global object. Basically, it refers to the current object.
35. What is the difference betweenstructure and a class?
Structure default access type is public , but class access type is private. A structure is used for grouping
data whereas class can be used for grouping data and methods. Structures are exclusively used for
dataand it doesnt require strict validation , but classes are used to encapsulates and inherit data which
requires strict validation.
36. What is the default access modifier in a class?
The default access modifier of a class is Private by default.
37. What is pure virtual function?
A pure virtual function is a function which can be overridden in the derived classbut cannot be defined. A
virtual function can be declared as Pure by using the operator =0.
Example -.
C#
Dynamic binding is a binding in which name can be associated with the class during execution time , and
it is also called as Late Binding.
46. How many instances can be created for an abstract class?
Zero instances will be created for an abstract class.
47. Which keyword can be used for overloading?
Operator keyword is used for overloading.
48. What is the default access specifier in a class definition?
Private access specifier is used in a class definition.
49. Which OOPS concept is used as reuse mechanism?
Inheritance is the OOPS concept that can be used as reuse mechanism.
50. Which OOPS concept exposes only necessary information to the calling functions?
Data Hiding / Abstraction
1. What is OOPS?
Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions"
and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data,
processes it, and produces output data.
2. basic Concepts of OOPs?
Abstraction.
Encapsulation.
Inheritance.
Polymorphism.
3. What is a class?
A set or category of things having some property or attribute in common and differentiated from others by kind, type,
or quality.
4. What is an object?
Objects are created from Classes, in C#, is an instance of a class that is created dynamically. Object is also a keyword
that is an alias for the predefined type System.
5. What is Encapsulation?
Encapsulation is the packing of data and functions into a single component. The features of encapsulation are
supported using classes in most object-oriented programming languages, although other alternatives also exist.
It allows selective hiding of properties and methods in an object by building an impenetrable wall to protect the code
from accidental corruption.
Also Read: Top 50 Common Job Interview Questions and answers
6. What is Polymorphism?
In programming languages and type theory, polymorphism is the provision of a single interface to entities of different
types.
A polymorphic type is a type whose operations can also be applied to values of some other type, or types.
7. What is Inheritance?
inheritance is when an object or class is based on another object or class, using the same implementation (inheriting
from a class) specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior).
It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and
interfaces.
8. What is Constructor?
A is special method of the class that will be automatically invoked when an instance of the class is created is called as
constructor.
Constructors are mainly used to initialize private fields of the class while creating an instance for the class.
When you are not creating a constructor in the class, then compiler will automatically create a default constructor in
the class that initializes all numeric fields in the class to zero and all string and object fields to null.
Syntax.
[Access Modifier] ClassName([Parameters])
{
}
9. Types of Constructors
Basically constructors are 5 types those are
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor
10. Define Destructor?
A destructor is a method which is automatically invoked when the object is destroyed.
Its main purpose is to free the resources (memory allocations, open files or sockets, database connections, resource
locks, etc.)
Also Read: Android Interview Ques & Ans for Fresher
11. What is Inline function?
In the C and C++ programming languages, an inline function is one qualified with the keyword inline; this serves two
purposes.
Firstly, it serves as a compiler directive, which suggests (but does not require) that the compiler substitute the body
of the function inline by performing inline expansion,
The second purpose of inline is to change linkage behavior; the details of this are complicated.
12. What is operator overloading?
In programming, operator overloadingless commonly known as operator ad hoc polymorphismis a specific case of
polymorphism, where different operators have different implementations depending on their arguments. Operator
overloading is generally defined by the language, the programmer, or both.
13. Different between method overriding and method overloading?
In Overriding methods it will create two or more methods with same name and same parameter in different classes.
while Overloading it will create more then one method with same name but different parameter in same class.
14. What is this keywords?
Every instance method in every object in Java receives a reference named this when the method is invoked. The
reference named this is a reference to the object on which the method was invoked. It can be used for any purpose
for which such a reference is needed.
15. What is super keyword?
The super keyword is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super
reference variable.
Also Read: Top 20 JSP Interview Questions and Answers
16. What is an abstract class?An abstract class is a class that is declared abstractit may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
17. What is final keywords?
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be: variable, method, class.
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable
or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only.
More question coming soon.. we are updating our list of ques and answer... :)
keep wait and watch for few days.
7. What is an Iterator?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This
interface allows you to walk through a collection of objects, operating on each object in turn.
Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained;
generally it is not advisable to modify the collection itself while traversing an Iterator.
8. State the significance of public, private, protected, default modifiers both singly and in combination and
state the effect of package relationships on declared items qualified by these modifiers.
public: Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the
variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that
owns the protected feature. This access is provided even to subclasses that reside in a different package from the
class that owns the protected feature.
What you get by default ie, without any access modifier (ie, public private or protected). It means that it is visible to
all within a particular package.
9. What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means
that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding
is done based on the type of the object, and static methods are attached to a class, not an object.
A static method in a superclass can be shadowed by another static method in a subclass, as long as the original
method was not declared final. However, you can't override a static method with a nonstatic method. In other words,
you can't change a static method into an instance method in a subclass.
10. What is final class?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its
class is inherited. You can't change value of a final variable (is a constant).
11. What if the main() method is declared as private?
The program compiles properly but at runtime it will give "main() method not public." message.
12. What if the static modifier is removed from the signature of the main() method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
13. What if I write static public void instead of public static void?
Program compiles and runs properly.
14. What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".
15. What is the first argument of the String array in main() method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is
the program name.
16. If I do not provide any arguments on the command line, then the String array of main() method will be empty
or null?
It is empty. But not null.
17. How can one prove that the array is not null but empty using one line of code?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown
a NullPointerException on attempting to print args.length.
18. What environment variables do I need to set on my machine in order to be able to run Java programs?
26. Does importing a package imports the subpackages as well? Example: Does importing com.MyTest.* also
import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the
package MyTest only. It will not import any class in any of it's subpackage.
27. What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means
declaration + initialization.
Example: String s; is just a declaration while String s = new String ("abcd"); Or String s =
"abcd"; are both definitions.
28. What is the default value of an object reference declared as an instance variable?
The default value will be null unless we define it explicitly.
29. Can a top level class be private or protected?
No. A top level class cannot be private or protected. It can have either "public" or no modifier. If it does not have a
modifier it is supposed to have a default access.
If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here".
This means that a top level class can not be private. Same is the case with protected.
30. What type of parameter passing does Java support?
In Java the arguments are always passed by value.
31. Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
32. Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the
original reference and parameter copy both refer to the same object.
33. What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
34. How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the
instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a
file.
35. Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any
methods.
36. How can I customize the seralization process? i.e. how can one have a control over the serialization
process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface.
This interface contains two methods namely readExternal and writeExternal.
You should implement these methods and write the logic for customizing the serialization process.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike
etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convense
the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we
don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.
Do You Know ?
Advantage of OOPs
Naming Convention
Object and class
Method overloading
Constructor
static keyword
this keyword with 6 usage
Inheritance
Aggregation
Method Overriding
Covariant Return Type
super keyword
Instance Initializer block
final keyword
Abstract class
Interface
Runtime Polymorphism
Static and Dynamic Binding
Downcasting with instanceof operator
Package
Access Modifiers
Encapsulation
Object Cloning
Java Tutorial
1. Java - What, Where and Why?
2. What is Java
3. Where Java is used
4. Java Applications
Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely used robust technology. Let's
start learning of java from basic questions like what is java tutorial, core java, where it is used, what type
of applications are created in java and why use java.
What is Java
Java Example
Let's have a quick look at java programming example. A detailed description of hello java example is given
in next page.
1. class Simple{
2.
public static void main(String args[]){
3.
System.out.println("Hello Java");
4.
}
5. }
Test it Now
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of
them are as follows:
1.
2.
3.
4.
5.
6.
7.
8.
1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to install
on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating
standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application. Currently,
servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage of high
level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile
applications.
Features of Java
1. Features of Java
1. Simple
2. Object-Oriented
3. Platform Independent
4. secured
5. Robust
6. Architecture Neutral
7. Portable
8. High Performance
9. Distributed
10. Multi-threaded
There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading
etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1.
2.
3.
4.
5.
6.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types of
platforms software-based and hardware-based. Java provides software-based platform. The Java
platform differs from most other platforms in the sense that it's a software-based platform that runs on
top of other hardware-based platforms.It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access right to
objects.
Security Manager- determines what resources a class can access such as reading and writing
to the local disk.
These security are provided by java language. Some security can also be provided by application
developer through SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that
avoids security problem. There is automatic garbage collection in java. There is exception handling and
type checking mechanism in java. All these points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat
slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares
the same memory. Threads are important for multi-media, Web applications etc.
C++ vs Java
There are many differences and similarities between C++ programming language and Java. A list of top
differences between C++ and Java are given below:
Comparison Index
Platform-
C++
Java
C++ is platform-dependent.
Java is platform-independent.
Java
programming.
independent
Mainly used for
is
mainly
web-based,
used
enterprise
for
application
and
mobile
applications.
Goto
Multiple
C++
inheritance
inheritance.
supports
multiple
Operator
C++
supports
Overloading
overloading.
operator
Pointers
Compiler
and
Call by reference
Structure
Interpreter
and
Union
unions.
Thread Support
C++
doesn't
have
built-in
C++
doesn't
support
comment
documentation comment.
Java
supports
documentation
comment
Virtual Keyword
C++
doesn't
>>>
operator.
support
>>>
Inheritance Tree
tree always.
To compile:
javac Simple.java
To execute:
java Simple
Output:Hello Java
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used print statement. We will learn about the internal working of
System.out.println statement later.
To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
notepad and write simple program as displayed below:
As displayed in the above diagram, write the simple program of java in notepad and saved it as
Simple.java. To compile and run this program, you need to open command prompt by start menu ->
All Programs -> Accessories -> command prompt.
To compile and run the above program, go to your current directory first; my current directory is c:\new
. Write here:
To compile:
javac Simple.java
To execute:
java Simple
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
If there occurs a problem like displayed in the below figure, you need to set path. Since DOS doesn't know
javac or java, we need to set path. Path is not required in such a case if you save your program inside the
jdk/bin folder. But its good approach to set path. Click here for How to set path in java.
Variable
Types of Variable
There
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.
Static variable
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Data Type
Default Value
Default size
boolean
false
1 bit
char
'\u0000'
2 byte
byte
1 byte
short
2 byte
int
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It
can be physical or logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to
write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
A class in java can contain:
data member
method
constructor
block
class and interface
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
As you see in the above figure, object gets the memory in Heap area and reference variable refers to
the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer
to the objects allocated in memory.
22. }
Output:55
45
are
By
By
By
By
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4.
int fact=1;
5.
for(int i=1;i<=n;i++){
6.
fact=fact*i;
7.
}
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
In java, Methood Overloading is not possible by changing the return type of the method.
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may
occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
1. class Calculation3{
2.
int sum(int a,int b){System.out.println(a+b);}
3.
double sum(int a,int b){System.out.println(a+b);}
4.
5.
public static void main(String args[]){
6.
Calculation3 obj=new Calculation3();
7.
int result=obj.sum(20,20); //Compile Time Error
8.
9.
}
10. }
Test it Now
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
1. class Overloading1{
2.
public static void main(int a){
3.
System.out.println(a);
4.
}
5.
6.
public static void main(String args[]){
7.
System.out.println("main() method invoked");
8.
main(10);
9.
}
10. }
Test it Now
Output:main() method invoked
10
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float
or double and so on.
Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
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.
of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.
Java Constructor
Constructor is used to initialize the state of an object.
Java Method
The java compiler provides a default constructor if you don't have any
constructor.
Constructor name must be same as the class name.
By constructor
By assigning the values of one object into another
By clone() method of Object class
Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
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.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22. }
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
Test it Now
Output:
111 Karan 0
222 Aryan 25
Java Constructor
Constructor is used to initialize the state of an object.
Java Method
The java compiler provides a default constructor if you don't have any
constructor.
Constructor name must be same as the class name.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21. }
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
Test it Now
Output:
111 Karan
111 Karan
13.
14.
15.
16.
17.
18.
19. }
Test it Now
Output:
111 Karan
111 Karan