0% found this document useful (0 votes)
15 views

Unit-2 Objects and Classes (E-Next - In)

The document discusses different types of constructors in Java including default, parameterized, copy constructor and constructor overloading. It also covers abstraction in Java and abstract classes with an example. Finally, it defines wrapper classes and provides examples of autoboxing and unboxing.

Uploaded by

deepak kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit-2 Objects and Classes (E-Next - In)

The document discusses different types of constructors in Java including default, parameterized, copy constructor and constructor overloading. It also covers abstraction in Java and abstract classes with an example. Finally, it defines wrapper classes and provides examples of autoboxing and unboxing.

Uploaded by

deepak kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit-2 Object and Classes

Q.1 What is constructor? Explain the types of constructor.


Q.2 What is Constructor? Explain Parameterized constructor and Constructor Overloading.
Constructor:
 Constructor are special methods which are used to initialize the object.
 A constructor has same name as that of class.
 It does not have any return type.
 e.g. class Rock
{
Rock() //default constructor
{ }
}
 If you do not provide the constructor then compiler create a default constructor.
 A default constructor is a non-argument constructor.
 If you create a constructor then compiler will not create default constructor for you.

Important points for constructor:


 Constructor are not inherited.
 They are called in the order of inheritance.
 They can be overloaded but can not be overridden.
 You can not create a single object without a constructor.
 ‘Super’ is use to call the desired version of superclass constructor.
 Call to the ‘super’ must be the first statement in constructor.
 ‘This’ keyword can be used for inter constructor communication.

Types of constructors:
1) Default constructor
2) Parameterized constructor

Default Constructor:
 A constructor that have no parameters is known as default constructor.
 It is primarily used to initialize the object with default initial values.
 When no default constructor is defined by users explicitly, java provides its own
version of default constructor to initialize the object.

 Syntax of Default Constructor:


 e.g. class Rock
{
Rock() //default constructor
{ }
}

Khan S. Alam 1 https://E-next.in


Unit-2 Object and Classes

Example of Default Constructor:

class A
{
A()
{
System.out.println(“In A Constructor”);
}
}

class B extends A
{
B()
{
System.out.println(“In B Constructor”);
}
}

class C extends B
{
C()
{
System.out.println(“In C Constructor”);
}

public static void main(String args[])


{
C ob = new c();
}
}

Output:
In A Constructor
In B Constructor
In C Constructor

Parameterized constructor:
 A constructor that have parameter is known as parameterized constructor.
 Parameter are added to a constructor in the way that they are added to a method,
just declare them inside the parentheses after the constructor’s name.
 Parameterized constructor is used to provide different values to the distinct objects.

Khan S. Alam 2 https://E-next.in


Unit-2 Object and Classes

Example of Parameterized Constructor:

class Student
{
int id;
String name;

Student(int i, String n) // Parameterized Constructor


{
id = i;
name = n;
}

void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Output:
111 Karan
222 Aryan

Constructor Overloading:
 Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists.
 The compiler differentiates these constructors by taking into account the number of
parameters in the list and their type.

Example of Constructor Overloading:

class Student
{
int id;
String name;
int age;

Khan S. Alam 3 https://E-next.in


Unit-2 Object and Classes

Student(int i, String n)
{
id = i;
name = n;
}

Student(int i, String n, int a)


{
id = i;
name = n;
age=a;
}

void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:
111 Karan
222 Aryan 25

Copy Constructor:
 There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
 There are many ways to copy the values of one object into another in java. They are:
1. By constructor
2. By assigning the values of one object into another
3. By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.

Khan S. Alam 4 https://E-next.in


Unit-2 Object and Classes

Example of Copy Constructor:

class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}

Student(Student s)
{
id = s.id;
name =s.name;
}

void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}

Output:
111 Karan
111 Karan

Khan S. Alam 5 https://E-next.in


Unit-2 Object and Classes

Q.3 Write a short notes on Abstract classes and Wrapper classes.


Q.4 Explain Wrapper classes with suitable program.
Abstraction in Java:
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 Another way, it shows only important things to the user and hides the internal
details for example sending sms, you just type the text and send the message. You
don't know the internal processing about the message delivery.
 Abstraction lets you focus on what the object does instead of how it does it.

Definition of Abstract Class:


 A class which contains the abstract keyword in its declaration is known as abstract
class.
 Abstract classes may or may not contain abstract methods , i.e., methods without
body ( public void get(); )
 But, if a class has at least one abstract method, then the class must be declared
abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.

Example of abstract class:


 abstract class A{}

Abstract method:
 A method that is declared as abstract and does not have implementation is known as
abstract method.

Example abstract method:


 abstract void printStatus(); //no body and abstract

Example of abstract class that has abstract method:


 In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}

class Honda extends Bike


{
void run()
{
System.out.println ("running safely..");

Khan S. Alam 6 https://E-next.in


Unit-2 Object and Classes

public static void main(String args[])


{
Bike obj = new Honda();
obj.run();
}
}

Output:
running safely..

Wrapper Class In Java:


 A wrapper class is a class whose object wraps or contains a primitive data types.
 Wrapper class in java provides the mechanism to convert primitive into object and
object into primitive.
 Autoboxing and unboxing feature converts primitive into object and object into
primitive automatically.
 The automatic conversion of primitive into object is known as autoboxing and vice-
versa unboxing.
 ln the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of
the abstract class Number.
 The object of the wrapper class contains or wraps its respective primitive data type.
 Converting primitive data types into object is called boxing, and this is taken care by
the compiler.
 Therefore, while using a wrapper class you just need to pass the value of the
primitive data type to the constructor of the Wrapper class.
 And the Wrapper object will be converted back to a primitive data type, and this
process is
 called unboxing.
 The Number class is part of the java.lang package.
 The eight classes of java.lang package are known as wrapper classes in java.

The list of eight wrapper classes are given below:

Wrapper Classes

Khan S. Alam 7 https://E-next.in


Unit-2 Object and Classes

Autoboxing:
 Automatic conversion of primitive types of the object of their corresponding
wrapper classes is known as autoboxing.
 For example:
 Conversion of int to Integer, long to Long, double to Double etc.

Wrapper class Example: Primitive to Wrapper

public class WrapperExample


{
public static void main(String args[])
{
int a=20;

Integer i=Integer.valueOf(a); //converting int into Integer


Integer j=a; //autoboxing,
//now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}

Output:
20 20 20

Unboxing:
 It is the reverse process of autoboxing.
 Automatically converting an object of a wrapper to its corresponding primitive type
is known as unboxing.
 For example:
 Conversion of Integer to int, Long to long, Double to double etc.

Wrapper class Example: Wrapper to Primitive

public class WrapperExample


{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a; //unboxing,
//now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
3 33

Khan S. Alam 8 https://E-next.in


Unit-2 Object and Classes

Q.5 What is Inheritance? Explain hybrid inheritance with suitable example.


Q.6 How do we achieve multiple inheritance in java? Explain with java program.
Q.7 Explain why java don’t support multiple inheritance. Write a program to demonstrate
use of Interface.
Inheritance in Java:
 Inheritance is one of the key features of object-oriented programming because it
allows the creation of hierarchical classifications.
 Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object.
 The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new methods and fields also.

Inheritance has advantages like:


 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.

Syntax of Java Inheritance:


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class.

Why multiple inheritance is not supported in java?


 To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
 Consider a scenario where A, B and C are three classes.
 The C class inherits A and B classes.
 If A and B classes have same method and you call it from child class object, there will
be ambiguity to call method of A or B class.
 Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes.
 So whether you have same method or different, there will be compile time error
now.

class A
{
void msg(){System.out.println("Hello");}
}

class B

Khan S. Alam 9 https://E-next.in


Unit-2 Object and Classes

{
void msg()
{
System.out.println("Welcome");
}
}

class C extends A,B


{ //suppose if it were
Public Static void main(String args[])
{
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}

Output:
Compile Time Error

Types of inheritance in java:


 On the basis of class, there are following types of inheritance supported in java:
1. Single Inheritance
2. Multiple Inheritance (Through Interface)
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (Through Interface)
 On the basis of class, there can be 3 types of inheritance in java: single, multilevel
and hierarchical.
 In java programming, multiple and hybrid inheritance is supported through interface
only.

1. Single Inheritance:
 Single Inheritance is the simple inheritance of all, when a class extends another class
(Only one class) then we call it as Single inheritance.
 The below diagram represents the single inheritance in java where Class B extends
only one class Class A. Here Class B will be the Sub class (child class) and Class A will
be one and only Super class (parent class).

Khan S. Alam 10 https://E-next.in


Unit-2 Object and Classes

Single Inheritance example program in Java


Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Output :
Base class method
Child class method

2. Multilevel Inheritance:
 Multilevel inheritance is a feature of oops concept, where a class is derived from
another derived class.
 As seen in the below diagram. ClassB inherits the property of ClassA and
again ClassB act as a parent for ClassC. In Short ClassA parent
for ClassB and ClassB parent for ClassC.

Khan S. Alam 11 https://E-next.in


Unit-2 Object and Classes

MultiLevel Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
ClassC c = new ClassC();
c.dispA();
c.dispB();
c.dispC();
}
}
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC

3. Hierarchical Inheritance:
 Hierarchical inheritance is a feature of oops concept, where more than one classes
are derived from one base class, one parent class is inherited by many sub classes.

Khan S. Alam 12 https://E-next.in


Unit-2 Object and Classes

Hierarchical Inheritance Example


public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
ClassB b = new ClassB();
b.dispB();
b.dispA();

ClassC c = new ClassC();


c.dispC();
c.dispA();

ClassD d = new ClassD();


d.dispD();
d.dispA();
}
}

Khan S. Alam 13 https://E-next.in


Unit-2 Object and Classes

Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA

4. Multiple Inheritance:
 Multiple inheritance is a feature of oops concept, where a class can inherit
properties of more than one parent class.
 It can be implemented by using Interface.
 Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted
complexity when further extending the class.
 Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.

5. Hybrid Inheritance:
 In simple term we can say that Hybrid Inheritance is a combination of Single and
Multiple inheritance.
 It can be implemented by using Interface.
 Flow diagram of the Hybrid inheritance will look like below. As you
can ClassA will be acting as the Parent class for ClassB & ClassC and ClassB &
ClassC will be acting as Parent for ClassD.

Khan S. Alam 14 https://E-next.in


Unit-2 Object and Classes

Q.8 Write a short note on Static keyword.


Q.9 Explain use of Static Variables and methods in Java.
Static keyword in Java:
 The static keyword in java is used for memory management mainly.
 We can apply java static keyword with variables, methods, blocks and nested class.
 The static keyword belongs to the class than instance of the class.
 The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1) Java static variable:


 If you declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc.
 The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable:


 It makes your program memory efficient (i.e it saves memory).

Example of static variable:


//Program of static variable

class Student
{
int rollno;
String name;
static String college ="Hirey";

Student8(int r, String n)
{
rollno = r;
name = n;
}

void display ()
{
System.out.println(rollno+" "+name+" "+college);
}

public static void main(String args[])


{
Student s1 = new Student(111,"alam");
Student s2 = new Student(222,"mark");

Khan S. Alam 15 https://E-next.in


Unit-2 Object and Classes

s1.display();
s2.display();
}
}

Output:
111 alam Hirey
222 mark Hirey

2) Java static method:


 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 static method can access static data member and can change the value of it.

Example of static method that performs normal calculation:


//Program to get cube of a given number by static method

class Calculate
{
static int cube(int x)
{
return x*x*x;
}

public static void main(String args[])


{
int result=Calculate.cube(5);
System.out.println(result);
}
}

Output:
125

Khan S. Alam 16 https://E-next.in


Unit-2 Object and Classes

Restrictions for static method:


There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.

class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}

Output:
Compile Time Error

3) Java static block:


 Is used to initialize the static data member.
 It is executed before main method at the time of classloading.

Example of static block:

class A
{
Static
{
System.out.println("static block is invoked");
}

public static void main(String args[])


{
System.out.println("Hello main");
}
}

Output:
static block is invoked
Hello main

Khan S. Alam 17 https://E-next.in


Unit-2 Object and Classes

Q.10 Write a short note on super keyword.


super keyword:
 The super keyword in java 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.

Usage of java super Keyword:


 super is used to refer immediate parent class instance variable.
 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.

1) super is used to refer immediate parent class instance variable:


//example of super keyword

class Vehicle
{
int speed=50;
}

class Bike extends Vehicle


{
int speed=100;

void display()
{
System.out.println(super.speed); //will print speed of Vehicle now
}

public static void main(String args[])


{
Bike b=new Bike();
b.display();
}
}

Output:
50

2) super is used to invoke parent class constructor:


class Vehicle
{
Vehicle()
{
System.out.println ("Vehicle is created");
}
}

Khan S. Alam 18 https://E-next.in


Unit-2 Object and Classes

class Bike extends Vehicle


{
Bike()
{
super(); //will invoke parent class constructor
System.out.println ("Bike is created");
}

public static void main (String args[])


{
Bike b=new Bike();
}
}

Output:
Vehicle is created
Bike is created

3) super can be used to invoke parent class method:


 The super keyword can also be used to invoke parent class method. It should be
used in case subclass contains the same method as parent class as in the example
given below:

class Person
{
void message()
{
System.out.println("welcome");
}
}

class Student extends Person


{
void message()
{
System.out.println ("welcome to java");
}

void display()
{
message(); //will invoke current class message() method
super.message(); //will invoke parent class message() method
}

public static void main (String args[])


{

Khan S. Alam 19 https://E-next.in


Unit-2 Object and Classes

Student16 s=new Student16();


s.display();
}
}

Output:
welcome to java
welcome

Q.11 Explain the difference between Method Overloading and Method Overriding.

No. Method Overloading Method Overriding


1) Method overloading is the example Method overriding is the example of run
of compile time polymorphism. time polymorphism.
2) Method overloading is performed within Method overriding occurs in two class.
class.
3) In case of method overloading, In case of method overriding, parameter
parameter must be different. must be same.
4) Inheritance is not involved. Inheritance is involved.
5) Method overloading is performed within Method overriding occurs in two
class. classes that have IS-A (inheritance)
relationship.
6) Method overloading is used to increase Method overriding is used to provide the
the readability of the program. specific implementation of the method
that is already provided by its super class.
7) In java, method overloading can't be Return type must be same or covariant in
performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
8) Example: Example:
1. class OverloadingExample 1. class Animal
2. { 2. {
3. static int add(int a,int b){return a+b; 3. void eat()
4. } 4. {
5. static int add(int a,int b,int c){return a+b5. System.out.println("eating...");}
+c; 6. }
6. } 7. class Dog extends Animal{
7. } 8. void eat()
9. {
System.out.println("eating bread...");
}
}

Khan S. Alam 20 https://E-next.in


Unit-2 Object and Classes

Q.12 Write a short note on inner class.


Inner Classes in Java:
 Java inner class is defined inside the body of another class.
 Java inner class or nested class is a class which is declared inside the class or
interface.
 We use inner classes to logically group classes and interfaces in one place so that it
can be more readable and maintainable.
 Additionally, it can access all the members of outer class including private data
members and methods.

Syntax of Inner class:


class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}

Advantage of java inner classes:


There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all
the members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.

Inner Classes Example:


 Creating an inner class is quite simple. You just need to write a class within a class.
Unlike a class, an inner class can be private and once you declare an inner class
private, it cannot be accessed from an object outside the class.

Following is the program to create an inner class and access it. In the given example, we
make the inner class private and access the class through a method.

Khan S. Alam 21 https://E-next.in


Unit-2 Object and Classes

Example of Inner class:

classOuter_Demo
{
int num;
// inner class

private class Inner_Demo


{
public void print()
{
System.out.println ("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner()
{
Inner_Demo inner = newInner_Demo();
inner.print();
}
}

public class My_class


{
public static void main (String args [])
{
// Instantiating the outer class
Outer_Demo outer =newOuter_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}
}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class,
display_Inner() is the method inside which we are instantiating the inner class, and this
method is invoked from the main method.
If you compile and execute the above program, you will get the following result

Output:
This is an inner class.

Khan S. Alam 22 https://E-next.in


Unit-2 Object and Classes

Q.13 Write java program to demonstrate use of final keyword.


final Keyword:
 The final keyword in java is used to restrict the user.
 The java final keyword can be used in many context.
 Final can be:
1) variable
2) method
3) 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.

1) Java final variable:


 If you make any variable as final, you cannot change the value of final variable (It will
be constant).

Example of final variable:


 There is a final variable speedlimit, we are going to change the value of this variable,
but it can't be changed because final variable once assigned a value can never be
changed.

class Bike
{
final int speedlimit=90; //final variable

void run()
{
speedlimit=400;
}

public static void main (String args [])


{
Bike obj = new Bike();
obj.run();
}
}
//end of class
Output:
Compile Time Error

Khan S. Alam 23 https://E-next.in


Unit-2 Object and Classes

2) Java final method:


 If you make any method as final, you cannot override it.
 final method is inherited but you cannot override it.

Example of final method:

class Bike
{
final void run()
{
System.out.println ("running");
}
}

class Honda extends Bike


{
void run()
{
System.out.println ("running safely with 100kmph");
}

public static void main (String args[])


{
Honda honda = new Honda();
honda.run();
}
}

Output:
Compile Time Error

Khan S. Alam 24 https://E-next.in


Unit-2 Object and Classes

3) Java final class:


 If you make any class as final, you cannot extend it.

Example of final class:

final class Bike


{}

class Honda1 extends Bike


{
void run()
{
System.out.println ("running safely with 100kmph");
}

public static void main (String args [])


{
Honda1 honda = new Honda();
honda.run();
}
}

Output:
Compile Time Error

Khan S. Alam 25 https://E-next.in


Unit-2 Object and Classes

Q.14 What is garbage collection? Explain the use of GC class? What is finalize method?
In java, garbage means unreferenced objects.
Garbage Collection:
 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.
 When an object is no longer used, the garbage collector reclaims the underlying
memory and reuses it for future object allocation.

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.

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()
{
}

Garbage Collector Method:


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 TestGarbage


{
public void finalize()
{
System.out.println ("object is garbage collected");
}

Khan S. Alam 26 https://E-next.in


Unit-2 Object and Classes

public static void main (String args[])


{
TestGarbage s1=new TestGarbage();
TestGarbage s2=new TestGarbage();
s1=null;
s2=null;
System.gc();
}
}

OUTPUT:
object is garbage collected
object is garbage collected

Q.15 Explain the difference between Interfaces and Abstract classes.

No. Interface Abstract class


1) Interface can have only abstract methods. Abstract class can have abstract and non-
Since Java 8, it can have default and static abstract methods.
methods also.
2) Interface supports multiple inheritance. Abstract class doesn't support multiple
inheritance.
3) Interface has only static and final variables. Abstract class can have final, non-final, static
and non-static variables.
4) Interface can't provide the implementation of Abstract class can provide the
abstract class. implementation of interface.
5) The interface keyword is used to declare The abstract keyword is used to declare
interface. abstract class
6) An interface can extend another Java An abstract class can extend another Java
interface only. class and implement multiple Java interfaces.
7) An interface class can be implemented using An abstract class can be extended using
keyword "implements". keyword "extends".
8) Members of a Java interface are public by A Java abstract class can have class members
default. like private, protected, etc.
9) Interface doesn’t contains Data Member. Abstract class contains Data Member.
10) Interface doesn’t contains constructors. Abstract class contains constructors.
11) Speed is slow. Speed is fast.
12) Example: Example:
public interface Drawable public abstract class Shape
{ {
void draw(); public abstract void draw();
} }

Khan S. Alam 27 https://E-next.in


Unit-2 Object and Classes

Q.16 Write a short note one string and mutable string.


Q.17 What is StringBuffer class? Write a program to append a string.
1) String in Java:
 In java, string is basically an object that represents sequence of char values. An array
of characters works same as java string.

For example:
1. char[] ch = {'j','a','v','a','t','p','o','i','n','t'};
2. String s = new String(ch);
is same as:
String s="javatpoint";

 Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
 The java.lang.String class implements Serializable, Comparable and CharSequence
interfaces.
 The CharSequence interface is used to represent sequence of characters. It is
implemented by String, StringBuffer and StringBuilder classes. It means, we can
create string in java by using
 these 3 classes.
 The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and
StringBuilder classes.

String in Java:
 Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters.
 The java.lang.String class is used to create string object.

There are two ways to create String object:


1. By string literal
2. By new keyword

1) String Literal:
 Java String literal is created by using double quotes.
For Example:
1. String s="welcome";
 Each time you create a string literal, the JVM checks the string constant pool first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
string doesn't exist in the pool, a new string instance is created and placed in the
pool.
For example:
1. String s1="Welcome";
2. String s2="Welcome"; //will not create new instance

Khan S. Alam 28 https://E-next.in


Unit-2 Object and Classes

2) By new keyword:
 1. String s=new String ("Welcome"); //creates two objects and one reference
variable
 In such case, JVM will create a new string object in normal (non pool) heap memory
and the literal "Welcome" will be placed in the string constant pool. The variable s
will refer to the object in heap (non pool).

Java String Example:

public class StringExample


{
public static void main(String args [])
{
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

Output:
java
strings
example

2) MUTABLE STRING:
 A string that can be modified or changed is known as mutable string.
 StringBuffer and StringBuilder classes are used for creating mutable string.

Java StringBuffer class:


 Java StringBuffer class is used to create mutable (modifiable) string.
 The StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed.
 Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Khan S. Alam 29 https://E-next.in


Unit-2 Object and Classes

Methods of the StringBuffer class:

1) StringBuffer append() method:


 The append() method concatenates the given argument with this string.
class StringBufferExample
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer ("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}

2) StringBuffer insert() method:


 The insert() method inserts the given string with this string at the given position.

class StringBufferExample2
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer ("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello
}
}

3) StringBuffer replace() method:


 The replace() method replaces the given string from the specified beginIndex and
endIndex.

class StringBufferExample3
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer ("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}

Khan S. Alam 30 https://E-next.in


Unit-2 Object and Classes

4) StringBuffer delete() method:


 The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex.

class StringBufferExample4
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}

5) StringBuffer reverse() method:


 The reverse() method of StringBuilder class reverses the current string.

class StringBufferExample5
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

Khan S. Alam 31 https://E-next.in


Unit-2 Object and Classes

Q.18 What is polymorphism?


Polymorphism:
 Polymorphism in java is a concept by which we can perform a single action by
different ways.
 Polymorphism is derived from 2 greek words: poly and morphs.
 The word “poly” means many and “morphs” means forms.
 So polymorphism means many forms. So it is the ability of an object to take on many
forms,
 The most common use of polymorphism is OOP occurs when a parent class
reference is used to refer to a child class object.
 There are two types of polymorphism in java:
1. Compile time polymorphism
2. Runtime polymorphism
 We can perform polymorphism in java by method overloading and method
overriding.

Method Overloading:
 Method with the same name but different parameters is known as method
overloading.

Method Overloading Example:

class Demo
{
public void show ()
{
System.out.println (“In show with Empty”);
}

public void show (int a)


{
System.out.println (“In show with parameter”+a);
}

public void show (int a, int b)


{
System.out.println (“In show with parameter”+a” ”+b);
}

Public static void main (string args [])


{
Demo ob = new Demo();
ob.show();
ob.show(5);
ob.show(10,20);
}}

Khan S. Alam 32 https://E-next.in


Unit-2 Object and Classes

Output:
In show with Empty
In show with parameter 5
In show with parameter 10 20

Method Overriding:
 Writing the method in the child class which has same name and signature as that of
parent class is known as method overriding.

Note: For overriding there should be atleast 2 classes having parent child relationship.
Return type is not the part of the signature.

Example of the Method Overriding:

class parent
{
void show()
{
System.out.println (“In parent show”);
}
}

class child extends parent


{
void show()
{
System.out.println (“In child show”);
}

Public static void main (string args [])


{
child ob = new child();
ob.show()
}
}

Output:
In child show

Khan S. Alam 33 https://E-next.in


Unit-2 Object and Classes

Q.19 Write a short note on this keyword.


this keyword:
 There can be a lot of usage of java this keyword. In java, this is a reference variable
that refers to the current object.
 Using this you can refer the members of a class such as constructors, variables and
methods.
 Note: The keyword this is used only within instance methods or constructors

Usage of java this keyword:


Here is given the 6 usage of java this keyword.
 this keyword can be used to refer current class instance variable.
 this() can be used to invoke current class constructor.
 this keyword can be used to invoke current class method (implicitly)
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this keyword can also be used to return the current class instance.

Example of this keyword:


class Student11
{
int id;
String name;

Student (int id, String name)


{
this.id = id;
this.name = name;
}

void display ()
{
System.out.println (id+" "+name);
}

public static void main (String args [])


{
Student s1 = new Student (111,"alam");
Student s2 = new Student (222,"mark");
s1.display();
s2.display();
}
}

Output:
111 alam
222 mark

Khan S. Alam 34 https://E-next.in

You might also like