Unit - 2
Classes and Objects
Q1) What is class?
A1) Class can be defined as the core part of Java. It is the basic construct in Java upon which the entire language is created since it defines the shape and nature of an object.
A class consist of group of objects having similar properties. It is a logical entity which can be more complex in nature.
Class Declaration
To declare a class, use the class keyword. A class can be defined as:
Class class_name{
Type obj_varaible1;
Type obj_variable2;
.....
Type obj_variableN;
Type method_name1(parameters){
//method body
}
....
Type method_nameN(parameters){
//method body
}
}
All the data or variables declare inside a class are known as instance variables. The actual logical resides within the methods. And the collection of methods and variables in class are known as members.
Example of Class
Consider an example of class student that has two instances name and grade. There is no method declaration.
Class Student{
String name;
Int grade;
}
Whenever a class is declare that means a template is created, it is not an actual object. Therefore, object creation and declaration we will see in further topics.
Similarly till now there is no method created in above example.
Q2) Define object?
A2) An object is an instance of class. In Java object can be defined as the physical as well as logical entity.
Objects can be described using three parameters:
● State is used to define the data or value of an object.
● Behavior represents the functionality of an object.
● Identity is used to assign a unique id to every object,
Creating an object
To create an object in Java a class is used.
Let’s take above example of class student. To create an object of student class, specify the class name followed by the object name and use the new keyboard.
Syntax to create an object is
Classname object_name = new classname();
See the objects mystud1 and mystud2 in the above example of Student class.
Accessing Instance variables and methods
User created objects can access the instance variables and methods. Following are the syntax to access instance variables and methods by objects:
/* object creation */
Classname object_name = new classname();
/* call a variable */
Object_name.variableName;
/* call a class method */
Object_name.MethodName();
Q3) Explain constructor?
A3) Constructors perform the job of initializing an object. It resembles a method in Java, but a constructor is not a method and it doesn’t have any return type.
Properties of a constructor:
1. Name of the constructor is the same as its class name.
2. A default constructor is always present in a class implicitly.
3. There are three main types of constructors namely default, parameterized and copy constructors.
4. A constructor in Java can not be abstract, final, static and Synchronized.
Public class NewClass{
//This is the constructor
NewClass(){
}}
The new keyword here creates the object of class NewClass and invokes the constructor to initialize this newly created object.
Default constructor:
A default constructor is a constructor that is created implicitly by the JVM.
Program to demonstrate default constructors:
Class student
{
Int id;
String name;
Student()
{
System.out.println("Student id is 20 and name is Amruta");
}
Public static void main(String args[])
{
Student s = new student();
}
}
Output:
Parameterized constructor:
It is a constructor that has to be created explicitly by the programmer. This constructor has parameters that can be passed when a constructor is called at the time of object creation.
Program:
Class Student4
{
Int id;
String name;
Student4(int i,String n)
{
Id = i;
Name = n;
}
Void display()
{
System.out.println(id+" "+name);
}
Public static void main(String args[])
{
Student4 s1 = new Student4(20,"Rema");
Student4 s2 = new Student4(23,"Sadhna");
s1.display();
s2.display();
}
}
Output:
Copy constructor:
A content of one constructor can be copied into another constructor using the objects created. Such a constructor is called as a copy constructor.
Program:
Class Student6
{
Int id;
String name;
Student6(int i,String n)
{
Id = i;
Name = n;
}
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(20,"AMRUTA");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:
Q4) What do you mean by constructor overloading?
A4) Like method overloading we can also do constructor overloading. Overloaded constructors in Java can be implemented in the same way as method overloading. We can have more than one constructor with different parameter list with same name. Each constructor performs a different task.
Compiler differentiates between each constructor on the basis of their parameter list.
Example of constructor loading is given below:
Class Add {
Int x;
Int y;
// Overloaded constructor takes two int parameters
Add(int a, int b)
{
x = a;
y = b;
}
// Overloaded constructor single int parameters
Add(int a)
{
x = y = a;
}
// Overloaded constructor takes no parameters
Add()
{
x = 6;
y = 5;
}
Int sum() {
Return x + y;
}
}
Class OverloadAdd{
Public static void main(String args[])
{
// create objects using the various constructors
Add cons1 = new Add(23, 1);
Add cons2 = new Add(8);
Add cons3 = new Add();
Int s;
s = cons1.sum()
System.out.println(“Sum of constructor1 =” + s);
s = cons2.sum()
System.out.println(“Sum of constructor2 =” + s);
s = cons3.sum()
System.out.println(“Sum of constructor3 =” + s);
}
}
Output
Sum of constructor1 = 24
Sum of constructor2 = 16
Sum of constructor3 = 11
Q5) Write about method overloading?
A5) If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
- By changing number of arguments
- By changing the data type
In Java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. Of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
- Class Adder{
- Static int add(int a,int b){return a+b;}
- Static int add(int a,int b,int c){return a+b+c;}
- }
- Class TestOverloading1{
- Public static void main(String[] args){
- System.out.println(Adder.add(11,11));
- System.out.println(Adder.add(11,11,11));
- }}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
- Class Adder{
- Static int add(int a, int b){return a+b;}
- Static double add(double a, double b){return a+b;}
- }
- Class TestOverloading2{
- Public static void main(String[] args){
- System.out.println(Adder.add(11,11));
- System.out.println(Adder.add(12.3,12.6));
- }}
Output:
22
24.9
Q6) Why Method Overloading is not possible by changing the return type of method only?
A6) In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
Let's see how ambiguity may occur:
- Class Adder{
- Static int add(int a,int b){return a+b;}
- Static double add(int a,int b){return a+b;}
- }
- Class TestOverloading3{
- Public static void main(String[] args){
- System.out.println(Adder.add(11,11));//ambiguity
- }}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the same method having same parameters.
Q7) Can we overload java main() method?
A7) Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
- Class TestOverloading4{
- Public static void main(String[] args){System.out.println("main with String[]");}
- Public static void main(String args){System.out.println("main with String");}
- Public static void main(){System.out.println("main without args");}
- }
Output:
Main with String[]
Q8) Explain recursion?
A8) Recursion is the process of a function calling itself directly or indirectly, and the associated function is known as a recursive function. Certain problems can be solved quickly using the recursive algorithm. Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, and others are examples of such issues.
In Java, recursion is the process of a method repeatedly calling itself. In Java, a recursive method is one that calls itself.
It makes the code small but difficult to comprehend.
Syntax:
Returntype methodname(){
//code to be executed
Methodname();//calling same method
}
Example
Public class RecursionExample2 {
Static int count=0;
Static void p(){
Count++;
If(count<=5){
System.out.println("hello "+count);
p();
}
}
Public static void main(String[] args) {
p();
}
}
Output
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Q9) Write a program for factorial numbers using recursion?
A9) Factorial number
Public class RecursionExample3 {
Static int factorial(int n){
If (n == 1)
Return 1;
Else
Return(n * factorial(n-1));
}
Public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Output
Factorial of 5 is: 120
Working of above program:
Factorial(5)
Factorial(4)
Factorial(3)
Factorial(2)
Factorial(1)
Return 1
Return 2*1 = 2
Return 3*2 = 6
Return 4*6 = 24
Return 5*24 = 120
Q10) Define a new operator?
A10) In Java, the new operator is used to create new objects. It's also possible to utilise it to make an array object.
Declaring a class in Java is essentially the same as defining a new data type. The blueprint for objects is provided by a class. A class can be used to make an object.
Let's have a look at the stages involved in constructing an object from a class.
Declaration - A variable declaration that includes a variable name and an object type.
Instantiation - The object is created with the help of the 'new' keyword.
Initialization - Initialization After the 'new' keyword, a call to a function Object() { [native code] } is made. The new object is initialised with this call.
Example
Public class Main {
Public static void main(String[] args) {
Double[] myList = new double[] {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
For (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
Double total = 0;
For (int i = 0; i < myList.length; i++) {
Total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
Double max = myList[0];
For (int i = 1; i < myList.length; i++) {
If (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Q11) Describe this and static keywords with examples?
A11) this Keyword
This keyword is a reference variable that refers to current object. It can be used in number of scenarios.
- Used to refer instance variable of the current class
- can be used in a constructor
- can be passed as an argument in the method call and constructor call
- can be used to invoke current class constructor
Program:
Class thisDemo
{
Int i;
Int j;
// Parameterized constructor
ThisDemo(int i, int j)
{
This.i = i;
This.j = j;
}
Void display()
{
System.out.println("i=" +i);
System.out.println("j=" +j);
}
Public static void main(String[] args)
{
ThisDemo object = new thisDemo(10, 20);
Object.display();
}
}
Output:
Static Keyword
Static keyword in Java is mainly used for memory management. We can use static keyword with variables, methods, blocks and nested classes.
The main purpose of using static keyword is in the case when we want to share the same variable or method of a given class without creating their instances.
To declare such variable or methods prefix the static keyword with the variable name or method name.
If a member is declared as static, that means it can be accessed before the creation of any object of that class and without need of any object reference.
The best example of static keyword is the main(). We declare it as static so that it must be called before the existence of any object.
One more advantage of using static is that if any variable is declared using static then no copy of static variable is made separately for the created objects. Instead all the objects of the class use the same static variable.
Besides this their few restrictions in case of static method:
● They can call only other static methods and not any other type of methods.
● Only static data can access them.
● They cannot use this or super keyword.
Example
Class DemoStatic {
Static int x = 4; //static variable
Static int y;
Static void abc(int i) { //static method
System.out.println("i = " + i);
System.out.println("x = " + x);
System.out.println("y = " + y);
}
Static { //static block
System.out.println(“Example of static block initialized”);
y = x * 4;
}
Public static void main(String args[]) {
Abc(8);
}
}
Output
Example of static block initialized.
i = 8
x = 4
y = 16
To use a static method outside a class, following syntax will be used:
Classname.methodname()
Q12) Write about modifiers?
A12) Basically, there are two types of modifiers in Java, access modifiers and non-access modifiers.
In Java there are four types of access modifiers according to the level of access required for classes, variable, methods and constructors. Access modifiers like public, private, protected and default.
Default Access Modifier
In this access modifier we do not specify any modifier for a class, variable, method and constructor.
Such types of variables or method can be used by any other class. There are no restrictions in this access modifier.
There is no syntax for default modifier as declare the variables and methods without any modifier keyword.
Example-
String name = “Disha”;
Boolean processName() {
Return true;
}
Private Access Modifier
This access modifier uses the private keyword. By using this access modifier the methods, variable and constructors become private and can only be accessed by the member of that same class.
It is the most restrict access specifier. Class and interface cannot be declared using the private keyword.
By using private keyword we can implement the concept of encapsulation, which hides data from the outside world.
Example of private access modifier
Public class ExampleAcces {
Private String ID;
Public String getID() {
Return this.ID;
}
Public void setID(String ID) {
This.ID = ID;
}
}
In the above example the ID variable of the ExampleAccess class is private, so no other class can retrieve or set its value easily.
So, to access this variable for use in the outside world, we defined two public methods: getID(), which returns the value of ID, and setID(String), which sets its value.
Public Access Modifier
As the name suggest a public access modifier can be easily accessed by any other class or methods.
Whenever we specify public keyword to a class, method, constructor etc, then they can be accessed from any other class in the same package. Outside package we have to import that class for access because of the concept of inheritance.
In the below example, function uses public access modifier:
Public static void main(String[] arguments) {
// ...
}
It is necessary to declare the main method as public, else Java interpreter will not be able to called it to run the class.
Protected Access Modifier
In this access modifier, in a superclass if variables, methods and constructors are declared as protected then only the subclass in other package or any class within the same package can access it.
It cannot be assigned to class and interfaces. In general method’s fields can be declared as protected: however methods and fields of interface cannot be defined as protected.
It cannot be defined on the class.
An example of protected access modifier is shown below:
Class Person {
Protected int ID(ID pid) {
// implementation details
}
}
Class Employee extends Person {
Int ID(ID pid) {
// implementation details
}
}
Q13) What do you mean by anonymous inner class?
A13) Anonymous class
- Java anonymous inner class is an inner class without a name and for which only a single object is created.
- An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.
- In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:
- Class (may be abstract or concrete).
- Interface
Java anonymous inner class example using class
TestAnonymousInner.java
Abstract class Person
{
Abstract void eat();
}
Class TestAnonymousInner
{
Public static void main(String args[])
{
Person p=new Person(){
Void eat()
{ System.out.println("nice fruits"); }
};
p.eat();
}
}
Output:
Nice fruit
Q14) What is abstract class?
A14) Abstract class
● Abstract classes are the same as normal Java classes the difference is only that an abstract class uses abstract keyword while the normal Java class does not use.
● We use the abstract keyword before the class name to declare the class as abstract.
● An abstract class contains abstract methods as well as concrete methods.
● If we want to use an abstract class, we have to inherit it from the base class.
● If the class does not have the implementation of all the methods of the interface, we should declare the class as abstract. It provides complete abstraction. It means that fields are public static and final by default and methods are empty.
The syntax of abstract class is:
Public abstract class ClassName
{
Public abstract methodName();
}
Example of car:
Abstract class Car
{ //abstract method
Abstract void start();
//non-abstract method
Public void stop()
{
System.out.println("The car engine is not started.");
}
} //inherit abstract class
Public class Owner extends Car
{ //defining the body of the abstract method of the abstract class
Void start()
{
System.out.println("The car engine has been started.");
}
Public static void main(String[] args)
{ Owner obj = new Owner();
//calling abstract method
Obj.start();
//calling non-abstract method
Obj.stop();
}
}
OUTPUT:
The car has been started.
The car engine is not started.
Abstract Method
The method that does not has method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the abstract class. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.
Syntax
- Abstract void method_name();
Q15) Write any example of abstract class?
A15) Example of abstract method
Demo.java
- Abstract class Demo //abstract class
- {
- //abstract method declaration
- Abstract void display();
- }
- Public class MyClass extends Demo
- {
- //method implementation
- Void display()
- {
- System.out.println("Abstract method?");
- }
- Public static void main(String args[])
- {
- //creating object of abstract class
- Demo obj = new MyClass();
- //invoking abstract method
- Obj.display();
- }
- }
Output:
Abstract method...
Q16) Write the advantages and needs of nested classes?
A16) Advantage of Java nestle classes
- Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
- Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
- Code Optimization: It requires less code to write.
Need of Java nested class
● Sometimes users need to program a class in such a way so that no other class can access it.
● Therefore, it would be better if you include it within other classes.
● If all the class objects are a part of the outer object then it is easier to nest that class inside the outer class.
● That way all the outer class can access all the objects of the inner class.
Q17) What is finalize() method?
A17) Finalize() is the method of Object class. This method is called just before an object is garbage collected. Finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.
Syntax
- Protected void finalize() throws Throwable
Throw
Throwable - the Exception is raised by this method
Example 1
- Public class JavafinalizeExample1 {
- Public static void main(String[] args)
- {
- JavafinalizeExample1 obj = new JavafinalizeExample1();
- System.out.println(obj.hashCode());
- Obj = null;
- // calling garbage collector
- System.gc();
- System.out.println("end of garbage collection");
- }
- @Override
- Protected void finalize()
- {
- System.out.println("finalize method called");
- }
- }
Output:
2018699554
End of garbage collection
Finalize method called
Q18) Write the difference between constructor overloading and method overloading?
A18) Difference between Constructor overloading and Method overloading
Constructor overloading | Method overloading |
Constructor Overloading is the practice of writing many constructors in a class, each with a distinct set of parameters. | Method overloading is the practise of writing many methods within a class, each with its own set of parameters. |
The class name will appear in all constructors. | The names of all methods must be the same. |
Overloaded constructor will be executed at the time of instantiating an object. | If the method is not static, it can only be invoked after the object has been created according to the requirements. |
An overloaded constructor cannot be static as a constructor relates to the creation of an object. | It is possible for an overloaded method to be static and to be accessed without having to create an object. |
An overloaded constructor cannot be final as the constructor is not derived by subclasses; it won't make sense. | To prevent subclasses from overriding an overloaded method, it can be made final. |
An overloaded constructor can be private to prevent using it for instantiating from outside of the class. | An overloaded method can be made private in order to prohibit outsiders from calling it. |
Unit - 2
Classes and Objects
Q1) What is class?
A1) Class can be defined as the core part of Java. It is the basic construct in Java upon which the entire language is created since it defines the shape and nature of an object.
A class consist of group of objects having similar properties. It is a logical entity which can be more complex in nature.
Class Declaration
To declare a class, use the class keyword. A class can be defined as:
Class class_name{
Type obj_varaible1;
Type obj_variable2;
.....
Type obj_variableN;
Type method_name1(parameters){
//method body
}
....
Type method_nameN(parameters){
//method body
}
}
All the data or variables declare inside a class are known as instance variables. The actual logical resides within the methods. And the collection of methods and variables in class are known as members.
Example of Class
Consider an example of class student that has two instances name and grade. There is no method declaration.
Class Student{
String name;
Int grade;
}
Whenever a class is declare that means a template is created, it is not an actual object. Therefore, object creation and declaration we will see in further topics.
Similarly till now there is no method created in above example.
Q2) Define object?
A2) An object is an instance of class. In Java object can be defined as the physical as well as logical entity.
Objects can be described using three parameters:
● State is used to define the data or value of an object.
● Behavior represents the functionality of an object.
● Identity is used to assign a unique id to every object,
Creating an object
To create an object in Java a class is used.
Let’s take above example of class student. To create an object of student class, specify the class name followed by the object name and use the new keyboard.
Syntax to create an object is
Classname object_name = new classname();
See the objects mystud1 and mystud2 in the above example of Student class.
Accessing Instance variables and methods
User created objects can access the instance variables and methods. Following are the syntax to access instance variables and methods by objects:
/* object creation */
Classname object_name = new classname();
/* call a variable */
Object_name.variableName;
/* call a class method */
Object_name.MethodName();
Q3) Explain constructor?
A3) Constructors perform the job of initializing an object. It resembles a method in Java, but a constructor is not a method and it doesn’t have any return type.
Properties of a constructor:
1. Name of the constructor is the same as its class name.
2. A default constructor is always present in a class implicitly.
3. There are three main types of constructors namely default, parameterized and copy constructors.
4. A constructor in Java can not be abstract, final, static and Synchronized.
Public class NewClass{
//This is the constructor
NewClass(){
}}
The new keyword here creates the object of class NewClass and invokes the constructor to initialize this newly created object.
Default constructor:
A default constructor is a constructor that is created implicitly by the JVM.
Program to demonstrate default constructors:
Class student
{
Int id;
String name;
Student()
{
System.out.println("Student id is 20 and name is Amruta");
}
Public static void main(String args[])
{
Student s = new student();
}
}
Output:
Parameterized constructor:
It is a constructor that has to be created explicitly by the programmer. This constructor has parameters that can be passed when a constructor is called at the time of object creation.
Program:
Class Student4
{
Int id;
String name;
Student4(int i,String n)
{
Id = i;
Name = n;
}
Void display()
{
System.out.println(id+" "+name);
}
Public static void main(String args[])
{
Student4 s1 = new Student4(20,"Rema");
Student4 s2 = new Student4(23,"Sadhna");
s1.display();
s2.display();
}
}
Output:
Copy constructor:
A content of one constructor can be copied into another constructor using the objects created. Such a constructor is called as a copy constructor.
Program:
Class Student6
{
Int id;
String name;
Student6(int i,String n)
{
Id = i;
Name = n;
}
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(20,"AMRUTA");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:
Q4) What do you mean by constructor overloading?
A4) Like method overloading we can also do constructor overloading. Overloaded constructors in Java can be implemented in the same way as method overloading. We can have more than one constructor with different parameter list with same name. Each constructor performs a different task.
Compiler differentiates between each constructor on the basis of their parameter list.
Example of constructor loading is given below:
Class Add {
Int x;
Int y;
// Overloaded constructor takes two int parameters
Add(int a, int b)
{
x = a;
y = b;
}
// Overloaded constructor single int parameters
Add(int a)
{
x = y = a;
}
// Overloaded constructor takes no parameters
Add()
{
x = 6;
y = 5;
}
Int sum() {
Return x + y;
}
}
Class OverloadAdd{
Public static void main(String args[])
{
// create objects using the various constructors
Add cons1 = new Add(23, 1);
Add cons2 = new Add(8);
Add cons3 = new Add();
Int s;
s = cons1.sum()
System.out.println(“Sum of constructor1 =” + s);
s = cons2.sum()
System.out.println(“Sum of constructor2 =” + s);
s = cons3.sum()
System.out.println(“Sum of constructor3 =” + s);
}
}
Output
Sum of constructor1 = 24
Sum of constructor2 = 16
Sum of constructor3 = 11
Q5) Write about method overloading?
A5) If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
- By changing number of arguments
- By changing the data type
In Java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. Of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
- Class Adder{
- Static int add(int a,int b){return a+b;}
- Static int add(int a,int b,int c){return a+b+c;}
- }
- Class TestOverloading1{
- Public static void main(String[] args){
- System.out.println(Adder.add(11,11));
- System.out.println(Adder.add(11,11,11));
- }}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
- Class Adder{
- Static int add(int a, int b){return a+b;}
- Static double add(double a, double b){return a+b;}
- }
- Class TestOverloading2{
- Public static void main(String[] args){
- System.out.println(Adder.add(11,11));
- System.out.println(Adder.add(12.3,12.6));
- }}
Output:
22
24.9
Q6) Why Method Overloading is not possible by changing the return type of method only?
A6) In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
Let's see how ambiguity may occur:
- Class Adder{
- Static int add(int a,int b){return a+b;}
- Static double add(int a,int b){return a+b;}
- }
- Class TestOverloading3{
- Public static void main(String[] args){
- System.out.println(Adder.add(11,11));//ambiguity
- }}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the same method having same parameters.
Q7) Can we overload java main() method?
A7) Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
- Class TestOverloading4{
- Public static void main(String[] args){System.out.println("main with String[]");}
- Public static void main(String args){System.out.println("main with String");}
- Public static void main(){System.out.println("main without args");}
- }
Output:
Main with String[]
Q8) Explain recursion?
A8) Recursion is the process of a function calling itself directly or indirectly, and the associated function is known as a recursive function. Certain problems can be solved quickly using the recursive algorithm. Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, and others are examples of such issues.
In Java, recursion is the process of a method repeatedly calling itself. In Java, a recursive method is one that calls itself.
It makes the code small but difficult to comprehend.
Syntax:
Returntype methodname(){
//code to be executed
Methodname();//calling same method
}
Example
Public class RecursionExample2 {
Static int count=0;
Static void p(){
Count++;
If(count<=5){
System.out.println("hello "+count);
p();
}
}
Public static void main(String[] args) {
p();
}
}
Output
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Q9) Write a program for factorial numbers using recursion?
A9) Factorial number
Public class RecursionExample3 {
Static int factorial(int n){
If (n == 1)
Return 1;
Else
Return(n * factorial(n-1));
}
Public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Output
Factorial of 5 is: 120
Working of above program:
Factorial(5)
Factorial(4)
Factorial(3)
Factorial(2)
Factorial(1)
Return 1
Return 2*1 = 2
Return 3*2 = 6
Return 4*6 = 24
Return 5*24 = 120
Q10) Define a new operator?
A10) In Java, the new operator is used to create new objects. It's also possible to utilise it to make an array object.
Declaring a class in Java is essentially the same as defining a new data type. The blueprint for objects is provided by a class. A class can be used to make an object.
Let's have a look at the stages involved in constructing an object from a class.
Declaration - A variable declaration that includes a variable name and an object type.
Instantiation - The object is created with the help of the 'new' keyword.
Initialization - Initialization After the 'new' keyword, a call to a function Object() { [native code] } is made. The new object is initialised with this call.
Example
Public class Main {
Public static void main(String[] args) {
Double[] myList = new double[] {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
For (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
Double total = 0;
For (int i = 0; i < myList.length; i++) {
Total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
Double max = myList[0];
For (int i = 1; i < myList.length; i++) {
If (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Q11) Describe this and static keywords with examples?
A11) this Keyword
This keyword is a reference variable that refers to current object. It can be used in number of scenarios.
- Used to refer instance variable of the current class
- can be used in a constructor
- can be passed as an argument in the method call and constructor call
- can be used to invoke current class constructor
Program:
Class thisDemo
{
Int i;
Int j;
// Parameterized constructor
ThisDemo(int i, int j)
{
This.i = i;
This.j = j;
}
Void display()
{
System.out.println("i=" +i);
System.out.println("j=" +j);
}
Public static void main(String[] args)
{
ThisDemo object = new thisDemo(10, 20);
Object.display();
}
}
Output:
Static Keyword
Static keyword in Java is mainly used for memory management. We can use static keyword with variables, methods, blocks and nested classes.
The main purpose of using static keyword is in the case when we want to share the same variable or method of a given class without creating their instances.
To declare such variable or methods prefix the static keyword with the variable name or method name.
If a member is declared as static, that means it can be accessed before the creation of any object of that class and without need of any object reference.
The best example of static keyword is the main(). We declare it as static so that it must be called before the existence of any object.
One more advantage of using static is that if any variable is declared using static then no copy of static variable is made separately for the created objects. Instead all the objects of the class use the same static variable.
Besides this their few restrictions in case of static method:
● They can call only other static methods and not any other type of methods.
● Only static data can access them.
● They cannot use this or super keyword.
Example
Class DemoStatic {
Static int x = 4; //static variable
Static int y;
Static void abc(int i) { //static method
System.out.println("i = " + i);
System.out.println("x = " + x);
System.out.println("y = " + y);
}
Static { //static block
System.out.println(“Example of static block initialized”);
y = x * 4;
}
Public static void main(String args[]) {
Abc(8);
}
}
Output
Example of static block initialized.
i = 8
x = 4
y = 16
To use a static method outside a class, following syntax will be used:
Classname.methodname()
Q12) Write about modifiers?
A12) Basically, there are two types of modifiers in Java, access modifiers and non-access modifiers.
In Java there are four types of access modifiers according to the level of access required for classes, variable, methods and constructors. Access modifiers like public, private, protected and default.
Default Access Modifier
In this access modifier we do not specify any modifier for a class, variable, method and constructor.
Such types of variables or method can be used by any other class. There are no restrictions in this access modifier.
There is no syntax for default modifier as declare the variables and methods without any modifier keyword.
Example-
String name = “Disha”;
Boolean processName() {
Return true;
}
Private Access Modifier
This access modifier uses the private keyword. By using this access modifier the methods, variable and constructors become private and can only be accessed by the member of that same class.
It is the most restrict access specifier. Class and interface cannot be declared using the private keyword.
By using private keyword we can implement the concept of encapsulation, which hides data from the outside world.
Example of private access modifier
Public class ExampleAcces {
Private String ID;
Public String getID() {
Return this.ID;
}
Public void setID(String ID) {
This.ID = ID;
}
}
In the above example the ID variable of the ExampleAccess class is private, so no other class can retrieve or set its value easily.
So, to access this variable for use in the outside world, we defined two public methods: getID(), which returns the value of ID, and setID(String), which sets its value.
Public Access Modifier
As the name suggest a public access modifier can be easily accessed by any other class or methods.
Whenever we specify public keyword to a class, method, constructor etc, then they can be accessed from any other class in the same package. Outside package we have to import that class for access because of the concept of inheritance.
In the below example, function uses public access modifier:
Public static void main(String[] arguments) {
// ...
}
It is necessary to declare the main method as public, else Java interpreter will not be able to called it to run the class.
Protected Access Modifier
In this access modifier, in a superclass if variables, methods and constructors are declared as protected then only the subclass in other package or any class within the same package can access it.
It cannot be assigned to class and interfaces. In general method’s fields can be declared as protected: however methods and fields of interface cannot be defined as protected.
It cannot be defined on the class.
An example of protected access modifier is shown below:
Class Person {
Protected int ID(ID pid) {
// implementation details
}
}
Class Employee extends Person {
Int ID(ID pid) {
// implementation details
}
}
Q13) What do you mean by anonymous inner class?
A13) Anonymous class
- Java anonymous inner class is an inner class without a name and for which only a single object is created.
- An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.
- In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:
- Class (may be abstract or concrete).
- Interface
Java anonymous inner class example using class
TestAnonymousInner.java
Abstract class Person
{
Abstract void eat();
}
Class TestAnonymousInner
{
Public static void main(String args[])
{
Person p=new Person(){
Void eat()
{ System.out.println("nice fruits"); }
};
p.eat();
}
}
Output:
Nice fruit
Q14) What is abstract class?
A14) Abstract class
● Abstract classes are the same as normal Java classes the difference is only that an abstract class uses abstract keyword while the normal Java class does not use.
● We use the abstract keyword before the class name to declare the class as abstract.
● An abstract class contains abstract methods as well as concrete methods.
● If we want to use an abstract class, we have to inherit it from the base class.
● If the class does not have the implementation of all the methods of the interface, we should declare the class as abstract. It provides complete abstraction. It means that fields are public static and final by default and methods are empty.
The syntax of abstract class is:
Public abstract class ClassName
{
Public abstract methodName();
}
Example of car:
Abstract class Car
{ //abstract method
Abstract void start();
//non-abstract method
Public void stop()
{
System.out.println("The car engine is not started.");
}
} //inherit abstract class
Public class Owner extends Car
{ //defining the body of the abstract method of the abstract class
Void start()
{
System.out.println("The car engine has been started.");
}
Public static void main(String[] args)
{ Owner obj = new Owner();
//calling abstract method
Obj.start();
//calling non-abstract method
Obj.stop();
}
}
OUTPUT:
The car has been started.
The car engine is not started.
Abstract Method
The method that does not has method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the abstract class. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.
Syntax
- Abstract void method_name();
Q15) Write any example of abstract class?
A15) Example of abstract method
Demo.java
- Abstract class Demo //abstract class
- {
- //abstract method declaration
- Abstract void display();
- }
- Public class MyClass extends Demo
- {
- //method implementation
- Void display()
- {
- System.out.println("Abstract method?");
- }
- Public static void main(String args[])
- {
- //creating object of abstract class
- Demo obj = new MyClass();
- //invoking abstract method
- Obj.display();
- }
- }
Output:
Abstract method...
Q16) Write the advantages and needs of nested classes?
A16) Advantage of Java nestle classes
- Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
- Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
- Code Optimization: It requires less code to write.
Need of Java nested class
● Sometimes users need to program a class in such a way so that no other class can access it.
● Therefore, it would be better if you include it within other classes.
● If all the class objects are a part of the outer object then it is easier to nest that class inside the outer class.
● That way all the outer class can access all the objects of the inner class.
Q17) What is finalize() method?
A17) Finalize() is the method of Object class. This method is called just before an object is garbage collected. Finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.
Syntax
- Protected void finalize() throws Throwable
Throw
Throwable - the Exception is raised by this method
Example 1
- Public class JavafinalizeExample1 {
- Public static void main(String[] args)
- {
- JavafinalizeExample1 obj = new JavafinalizeExample1();
- System.out.println(obj.hashCode());
- Obj = null;
- // calling garbage collector
- System.gc();
- System.out.println("end of garbage collection");
- }
- @Override
- Protected void finalize()
- {
- System.out.println("finalize method called");
- }
- }
Output:
2018699554
End of garbage collection
Finalize method called
Q18) Write the difference between constructor overloading and method overloading?
A18) Difference between Constructor overloading and Method overloading
Constructor overloading | Method overloading |
Constructor Overloading is the practice of writing many constructors in a class, each with a distinct set of parameters. | Method overloading is the practise of writing many methods within a class, each with its own set of parameters. |
The class name will appear in all constructors. | The names of all methods must be the same. |
Overloaded constructor will be executed at the time of instantiating an object. | If the method is not static, it can only be invoked after the object has been created according to the requirements. |
An overloaded constructor cannot be static as a constructor relates to the creation of an object. | It is possible for an overloaded method to be static and to be accessed without having to create an object. |
An overloaded constructor cannot be final as the constructor is not derived by subclasses; it won't make sense. | To prevent subclasses from overriding an overloaded method, it can be made final. |
An overloaded constructor can be private to prevent using it for instantiating from outside of the class. | An overloaded method can be made private in order to prohibit outsiders from calling it. |