Frequently asked questions on java programming language part-1
Question: How to prevent a class from inheritance without using final modifier
Answer: A class can be prevented from inheritance by defining a private
constructor
constructor
class Foo
{
// it is a private constructor
// so cant be called from outside the class Foo
private Foo()
{
}
}
class Doo extends Foo // it is wrong
{
}
reason of this : the constructor of sub-class automatically invokes the
constructor of super-class (using super keyword), and we know that private
things cant be accessed outside the class
Question: What is copy constructor and how to implement it in java
Answer: A copy constructor takes an object as an input and initialize new object
by coping its data into new object
[object] ==> [copy-constructor] ==> [new-object]
example,
class Foo
{
// a non static variable
int i;
// a no argument constructor
// i will not call this constructor in my code
// it is just defined
Foo()
{
i = 1;
}
// a paremeterized constructor
Foo(int i)
{
this.i = i;
}
// this is a copy constructor
// here we are taking a reference-variable 'f1' of class Foo
Foo(Foo f)
{
// copy the values of object 'f' one by one inside
// the current object (which is being initialized)
// 'this' means current object
this.i = f.i;
}
// define main method
public static void main(String[] args)
{
// create an object 'f1' by using paremeterized constructor
// look here, we are passing int value inside constructor
Foo f1 = new Foo(100);
// create an object 'f2' by using copy constructor
// look here, we are passing object-name 'f1' inside constructor
Foo f2 = new Foo(f1);
// note: the object 'f1' and 'f2' will have same data but with
// different address
}
}
Sir u make the things easier to understand
ReplyDeleteThis is very important and imformative blog for Java .It's very interesting and useful for students
ReplyDeleteJava Online Course