Unit - 2
Introducing 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 Static method.
A8)
Static method
Any method that uses the static keyword is referred to as a static method.
- A class's static method, rather than the class's object, belongs to the class.
- A static method can be called without having to create a class instance.
- A static method can access and update the value of a static data member.
Example:
//Java Program to demonstrate the use of a static method.
Class Student{
Int rollno;
String name;
Static String college = "ITS";
//static method to change the value of static variable
Static void change(){
College = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
Rollno = r;
Name = n;
}
//method to display values
Void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
Public class TestStaticMethod{
Public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Q9) What is wrapper class?
A9)
The use of wrapper class in Java is to convert primitive types into object and object into primitive type. They are needed because Java is designed on the concept of object.
Need of Wrapper classes
- To convert the primitive data type into objects.
- Java provides the package name java.util.package which consists of all classes used to handle wrapper class.
- There are such data structures like ArrayList and Vector which doesn’t store primitive type, they only store Objects. Here we need wrapper class.
- It helps in synchronization of multithreading.
Different predefined wrapper classes
In Java, the java.lang package consist of total eight wrapper classes. These classes are:
Primitive Type | Wrapper class |
Boolean | Boolean |
Char | Character |
Byte | Byte |
Short | Short |
Int | Integer |
Long | Long |
Float | Float |
Double | Double |
Example of wrapper class
Public class Wrapper Demo {
public static void main(String[] args) {
Integer myInt = 7;
Double myDouble = 8.1;
Character myChar = 'D';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
Output
7
8.1
D
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) Explain Garbage collection.
A13)
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
- It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
- It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
- By nulling the reference
- By assigning a reference to another
- By anonymous object etc.
Fig: How can an object be unreferenced?
1) By nulling a reference:
- Employee e=new Employee();
- e=null;
2) By assigning a reference to another:
- Employee e1=new Employee();
- Employee e2=new Employee();
- e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
- New Employee();
Finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
Protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
Gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
- Public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.
Simple Example of garbage collection in java
- Public class TestGarbage1{
- Public void finalize(){System.out.println("object is garbage collected");}
- Public static void main(String args[]){
- TestGarbage1 s1=new TestGarbage1();
- TestGarbage1 s2=new TestGarbage1();
- s1=null;
- s2=null;
- System.gc();
- }
- }
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.
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. |