Unit-2 Objects and Classes (E-Next - In)
Unit-2 Objects and Classes (E-Next - In)
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.
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”);
}
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.
class Student
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
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.
class Student
{
int id;
String name;
int age;
Student(int i, String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
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.
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);
}
Output:
111 Karan
111 Karan
Abstract method:
A method that is declared as abstract and does not have implementation is known as
abstract method.
Output:
running safely..
Wrapper 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.
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.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
The extends keyword indicates that you are making a new class that derives from an existing
class.
class A
{
void msg(){System.out.println("Hello");}
}
class B
{
void msg()
{
System.out.println("Welcome");
}
}
Output:
Compile Time Error
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).
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.
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.
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.
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);
}
s1.display();
s2.display();
}
}
Output:
111 alam Hirey
222 mark Hirey
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
Output:
125
class A
{
int a=40;//non static
public static void main(String args[])
{
System.out.println(a);
}
}
Output:
Compile Time Error
class A
{
Static
{
System.out.println("static block is invoked");
}
Output:
static block is invoked
Hello main
class Vehicle
{
int speed=50;
}
void display()
{
System.out.println(super.speed); //will print speed of Vehicle now
}
Output:
50
Output:
Vehicle is created
Bike is created
class Person
{
void message()
{
System.out.println("welcome");
}
}
void display()
{
message(); //will invoke current class message() method
super.message(); //will invoke parent class message() method
}
Output:
welcome to java
welcome
Q.11 Explain the difference between Method Overloading and Method Overriding.
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.
classOuter_Demo
{
int num;
// inner class
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.
class Bike
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400;
}
class Bike
{
final void run()
{
System.out.println ("running");
}
}
Output:
Compile Time Error
Output:
Compile Time Error
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.
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()
{
}
OUTPUT:
object is garbage collected
object is garbage collected
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.
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
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).
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.
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
}
}
class StringBufferExample3
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer ("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
class StringBufferExample4
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
class StringBufferExample5
{
public static void main(String args [])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Method Overloading:
Method with the same name but different parameters is known as method
overloading.
class Demo
{
public void show ()
{
System.out.println (“In show with Empty”);
}
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.
class parent
{
void show()
{
System.out.println (“In parent show”);
}
}
Output:
In child show
void display ()
{
System.out.println (id+" "+name);
}
Output:
111 alam
222 mark