Unit 3 Combined
Unit 3 Combined
Field declaration:
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variables because they are created whenever an object of the
class is instantiated. We can declare the instance variables exactly the same way we declare a local
variables.
ex:
class rectangle
{
int length;
int width;
}
The class rectangle contains two integer type instance variables. Instance variables are also known
as member variables.
Methods declaration:
Methods must be declared inside the body of the class immediately after the declaration of instance
variables. The general form of a method declaration is
type methodname(parameter-list)
{
method - body;
}
Method declarations have four basic parts
1. The name of the method (methodname)
2. The type of the value the method returns (type)
3. A list of parameters (parameter - list)
4. The body of the method (Method-body)
The parameter list is always enclosed in parentheses. The variables in the list are separated by
commas.
E.g.
class rectangle
{
int length, width;
void getData(int x, int y)
{
length = x;
width=y;
}
int rectArea()
{
int area = length*width;
return (area);
}
}
Explain how to create Objects and how class members are Accessed?
An Objects in Java is essentially a block of memory that contains space to store all the instance
variables. Creating an object is also referred to as instantiating an object.
Objects in Java are created using the “new” operator. The new operator creates an object of the
specified class and returns a reference to that object. Here is an example of creating an object of type
Rectangle.
Rectangle rectl; /*Declaring the object name*/
rect1= new Rectangle(); /*Instantiate the object*/
The first statements declares a variables to hold the object reference and the second one actually
assigns the object reference to the variable. The variable rect1 is now an object of the Rectangle class
Both statements can be combined into one as shown below:
Rectangle rect1 = new Rectangle ();
The method Rectangle() is the default constructor of that class, we can create any number of
objects of Rectangle.
Rectangle rect1= new Rectangle ();
Rectangle rect2: = new Rectangle ();
It is important to understand that each object has its own copy of the instance variables of its class.
This means that any changes to the variables of one object have no effect on the variables of another.
It is also possible to create two or more references to the same object as shown below
3. Copy Constructors: We can copy the values of object into another object, this type of constructor
known as copy constructor. This constructor can take only one parameter, which is a reference to an
object of the same class.
Program:
class Test
{
double x, y;
Test(double a, double b)
{
x = a;
y = b;
}
Test (Test a)
{
x = a.x;
y = a.y;
}
void show()
{
System.out.println(" X = " + x + " Y = " + y);
}
}
public class CopyConstructors
{
public static void main(String args[])
{
Test a=new Test(949120, 2987);
a.show();
Test b=new Test(a);
b.show();
}
}
Save: CopyConstructors.java
Compile: javac CopyConstructors.java
Run: java CopyConstructors
Output: X = 949120.0 Y = 2987.0
X = 949120.0 Y = 2987.0
Method Overloading:
In Java, it is possible to use a method name more than one time for definitions. A method can be
defined with same name but with different parameters list and different definitions.
The process of implementing one method with different number of parameters and different
definitions in a program is called “Method Overloading”, this process is a kind of “Polymorphism”.
To create an overloaded method, we need to provide several different method definitions with
the same name but with different parameter lists. The return type of the method is not considered in
overloading a method. The programmer should consider the following three rules to overload a method.
1. All the definition of an overloaded method must be differed either in the number of arguments
or type of arguments.
2. If the number of arguments is same for any two methods definitions, the type of arguments must
be different from each other.
3. If the number and types of arguments are same, the order of the arguments must be differed.
Write a Java program to calculate the area of room using Method Overloading?
class MethodOverload
{
void area (float x)
{
float al = x*x;
System.out.println ("The area of square is" + al);
}
void area (float x, float y)
{
float a2 = 1/2*x*y;
System.out.println ("The area of Triangle = "+a2);
}
void area (double x)
{
double a3 = 3.142*x*x;
System.out.println ("The area of circle = "+a3);
}
}
public class Overload
{
public static void main (String args[])
{
MethodOverload obj = new MethodOverload();
obj.area (5);
obj.area (11.0f,12.0f);
obj.area (2.5);
}
}
Output:
The area of square is 25.0
The area of Triangle = 0.0
The area of circle = 19.6375
Destructor:
In Java, when we create an object of the class it occupies some amount of memory (heap). If we
do not delete these objects, it remains in the memory and occupies unnecessary. To resolve this problem,
we use the destructor.
The destructor is the opposite of the constructor. The constructor is used to initialize objects while
the destructor is used to delete or destroy the object that releases the memory occupied by the object.
Java uses the concept of garbage collector that works the same as the destructor as there is no
concept of destructor in java. The garbage collector is a program (thread) that runs on the JVM. It
automatically deletes the unused objects (objects that are no longer used) and free-up the memory.
It is a special method that automatically gets called when an object is no longer used. When an
object completes its life-cycle the garbage collector deletes that object and deallocates or releases the
memory occupied by the object. Garbage collector runs finalize method hence we write our code in
finalize method.
Advantages:
1. It releases the resources occupied by the object.
2. No explicit call is required, it is automatically invoked at the end of the program execution.
3. It does not accept any parameter and cannot be overloaded.
Program:
public class DestructorExample
{
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
de.finalize();
de = null;
System.gc();
System.out.println("Inside the main() method");
}
protected void finalize()
{
System.out.println("Object is destroyed by the Garbage Collector");
}
}
Output:
Object is destroyed by the Garbage Collector
Inside the main() method
Object is destroyed by the Garbage Collector
Access Modifiers
Public Protected Default Private Private
Access Location (Friendly) Protected
Same Class. Yes Yes Yes Yes Yes
Sub Class in same package. Yes Yes Yes Yes No
1. Single Inheritance: Derivation of a class from only one super class is called single inheritance.
B
Child / Subclass / Derived class
3. Hierarchical Inheritance: Deriving multiple classes based on the one Existing Class is
called Hierarchical Inheritances.
B C D
4. Multiple Inheritances: Deriving of a class from several Base Classes is called as Multiple
Inheritances. Multiple Inheritances allows us to combine the features of several existing classes.
A B
B
Child / Subclass / Derived class
In Single inheritance derived class has the ability to inherit the member functions and
variables of the existing superclass.
Syntax:
class SuperClassA
{
----------
----------
}
class SubClassB extends SuperClass A
{
----------
----------
}
The keyword extends signifies that the properties of superclass are extended to the subclass. Now
the subclass contains its own variables, methods as well as the members of the super class
Program:
import java.util.*;
class Room
{
int length;
int breadth;
Room(int l, int b) // Parameterized Constructor
{
length=x;
breadth=y;
}
int area()
{
return length * breadth;
}
}
class GuestRoom extends Room // GuestRoom Inherits properties from Room
Class.
{
int height;
GuestRoom(int l, int b, int h)
{
super(l,b); // Pass Values to Superclasses
height=h;
}
int volume()
{
return (length*breadth*height); // Accessing Super Class Members.
}
}
public class SingleInheritance
{
public static void main (String args[])
{
GuestRoom myRoom = new GuestRoom(10,20,30); // Derived Class Object.
int area = myRoom.area(); // Accessing Super Class Method.
int volume = myRoom.volume(); // Accessing Sub Class Method.
System.out.println("Room Area = " + area);
System.out.println("Room Volume = " + volume);
}
}
Save: SingleInheritance.java
Compile: javac SingleInheritance.java
Run: java SingleInheritance
Output: Room Area = 200
Room Volume = 6000
The class A is a super class for the class B which in turn serves as a super class for the sub class
C. The chain A B C is known as inheritance path.
Syntax of Multilevel Inheritance:
class SuperClass A
{
----------
----------
}
class SubClass B extends SuperClass A
{
----------
----------
}
class SubClass C extends SuperClass B
{
----------
----------
}
Program:
class Student
{
int rollno;
String studname;
Student(int r, String n)
{
rollno = r;
studname = n;
}
void displayStudent()
{
System.out.println("Student Roll Number: " + rollno);
System.out.println("Student Name: "+ studname);
}
}
class Marks extends Student
{
int total;
Marks(int r, String n, int tot)
{
super(r, n);
total = tot;
}
void displayMarks()
{
displayStudent();
System.out.println("Student Total Marks: " + total);
}
}
class Percentage extends Marks
{
int per;
Percentage(int r, String n, int t, int p)
{
super(r, n,
t); per = p;
}
void displayPercentage()
{
displayMarks();
System.out.println(“Percentage of Marks: " +per);
}
}
class MultiLevelInheritance
{
B C D
Program:
class A
{
public void methodA()
{
System.out.println("Method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("Method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("Method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("Method of Class D");
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class
A obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Save: HierarchicalInheritance.java
Compile: javac HierarchicalInheritance.java
Run: java HierarchicalInheritance
Output: Method of Class A
Method of Class A
Method of Class A
(Q). Why Multiple Inheritance is not support in Java? (or) Explain how to achieve Multiple
Inheritances in Java?
Deriving of a class from several Base Classes is called as Multiple Inheritances. Multiple Inheritances
allows us to combine the features of several existing classes.
A B
In Java it is not possible to derive a new class based on more than one class directly; rather we
can use Interfaces to achieve this technique.
If two super classes have same names for their members (Variables and Methods) then
which member is inherited into the sub class is the main confusion in multiple inheritances.
This is the reason; Java does not support the concept of multiple inheritances.
This confusion is reduced by using multiple interfaces to achieve multiple inheritances.
Write a Java Program to Illustrate Unsupportance of Multiple Inheritance Diamond Problems
Similar Scenario?
import java.io.*;
class GrandParent
{
void fun()
{
System.out.println("Grand Parent Class");
}
}
class Father extends GrandParent
{
void fun()
{
System.out.println("Father Class");
}
}
class Son extends GrandParent
{
void fun()
{
System.out.println("Son Class");
}
}
// Class 4: Inheriting from multiple classes
class MultipleInheritance extends Father, Son
{
public static void main(String args[])
{
MultipleInheritance Family = new MultipleInheritance();
Family.fun();
}
}
NOTE: Creating object of this class in main() method Now calling fun() method from its father
& son classes which will throw compilation error.
Write a Java program to illustrate the Room Area and Room Volume using Super class
constructor?
import java.util.*;
class Room
{
int l, b;
Room(int x, int y)
{
l = x; b = y;
}
int area()
{
return (l * b);
}
}
class GuestRoom extends Room // GuestRoom Inherits properties from Room Class.
{
int h;
GuestRoom(int x, int y, int z)
{
super(x, y); // Pass Values to Superclasses.
h = z;
}
int volume() // Sub Class
{
return (l * b * h); // Accessing Super Class Members.
}
}
public class SuperInheritances
{
public static void main (String args[])
{
GuestRoom myRoom = new GuestRoom(5, 10, 20); // Derived Class Object.
int area = myRoom.area(); // Accessing Super Class Method.
int volume = myRoom.volume(); // Accessing Sub Class Method.
System.out.println("Room Area = " + area);
System.out.println("Room Volume = " + volume);
}
}
Save: SuperInheritances.java
Compile: javac SuperInheritances.java
Run : java SuperInheritances
Advantages of Inheritances:
Inheritance promotes reusability. When a class inherits or derives another class, it can access all
the functionality of inherited class.
Reusability enhanced reliability. The base class code will be already tested and debugged.
As the existing code is reused, it leads to less development and maintenance costs.
Inheritance makes the sub classes follow a standard interface.
Inheritance helps to reduce code redundancy and supports code extensibility.
Inheritance facilitates creation of class libraries.
Protected Specifier:
The private members of the superclass are not available to sub classes directly. But
sometimes, they may be a need to access the data of superclass in the sub class. For this purpose
protected specifier is used. Protected is commonly used in super class to make the members of the
super class available directly in its sub classes.
Polymorphism
Definition:
Polymorphism comes from the Greek word “Poly” & “Morphism”. “Poly” means Many or Several
and “Morphism‟ means Forms. The ability to exist in different forms is called polymorphism. In object-
oriented programming Polymorphism refers to identically name methods have different behavior
depending on the type of the Object.
(Or)
Polymorphism means is the process of representing different entities with the same name however
their behavior depends on the context.
Shape
Draw()
In above figure illustrates that a single function named as Draw() can be used to handle different
number of arguments.
Types of Polymorphsim:
Java supports Method Overriding and Overloading which are two forms of polymorphism they are as
follows.
Static Polymorphism:
“The polymorphism exhibited at Compilation time is called Static Polymorphism”. Here
the Java compiler knows without any confusion which method is called at the time of compilation.
JVM executes the method later, but the compiler can bind the method call with method code (body)
at the time of compilation. So, it is also called “Static Binding” or “Compile time Polymorphism”.
Dynamic Polymorphism:
The Polymorphism exhibited at Runtime is called Dynamic Polymorphism”. This means when a
method is called, the method call is bound to the method body at the time of running the program,
dynamically. In this case, Java compiler does not know which method is called at the time of
compilation. So it is also called as runtime polymorphism or dynamic binding.
Method Overloading:
The process of defining methods with same name but with different task is called as method
overloading.
To create an overloaded method, we need to write several methods with same name but
with different parameter lists. The programmer should consider the following three rules to overload
a method.
1. Overloaded methods must be differed either in the number of arguments or type of arguments.
2. If the number of arguments is same for any two methods definitions, the type of arguments must
be different from each other.
3. If the number and types of arguments are same, the order of the arguments must be differed.
Program:
import java.util.*; class
Room
{
float length;
float
breadth;
float roomArea(float l, float b) // Method accepts two parameters of type 'float'.
{
length = l;
breadth = b;
return length * breadth;
}
int roomArea(int l, int b) // Method accepts two parameters of type 'int'.
{
length = l;
breadth = b;
return length*breadth;
}
float roomArea(float l) // Method accepts one parameters of type 'float'.
{
length = breadth = l;
return length *
breadth;
}
Room r1 = new Room();
float a = r1.roomArea(2.5f, 5.5f);
int b = r1.roomArea(2, 5);
float c = r1.roomArea(7.5f);
}
Save: Room.java
Compile: javac Room.java
Run: java Room
Output: 13.75
10
56.25
Method Overriding:
Defining of a method in the subclass which is already defined in its superclass is called
as
“Overriding Method or Method Overriding”.
Method overriding means both the super class and sub class contain same method name with
same number of parameters and same return type.
Rules for Overriding a Method:
1. The name of the Overriding method is same as the method in superclass.
2. The return type of the Overriding method is same as of the method in superclass.
3. The number of argument of the Overriding method is same as the superclass.
4. The method declares “static” cannot be overridden but can be re-declared.
5. We cannot override a method which is declared as „final‟ in the superclass.
6. The invisible methods are cannot be Overridden.
7. Constructors cannot be overridden.
Program:
import java.util.*;
class simple
{
public void display()
{
System.out.println("Overriding methods");
}
}
class overrideclass extends Simple
{
public void display()
{
super.display();
System.out.println("Overriding simple class method");
}
}
class overridetest
{
public static void main(String args[])
{
overrideclass obj=new overrideclass();
obj.display();
}
}
Output:
overriding methods
overriding simple class method
Compare between Method Overloading and Method Overriding: