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

Unit 3 Combined

Uploaded by

Vignana Deepthi
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)
7 views

Unit 3 Combined

Uploaded by

Vignana Deepthi
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/ 26

Classes And Objects

What is a class and how it is defined:


A class is a user defined data type used to define the behaviour of the object. Classes create objects
and objects uses methods to communicate between them.
A class is used to define the objects data and functions. Once the class has been defined, we can
create the variable of the type using declaration statemen that are similar to basic data type declaration.
These variables are called as objects. The general form of class definition is as follows

class classname [extends superclassname]


{
fields declaration;
methods declaration;
}
classname and superclassname are any valid Java identifiers. The keyword extends indicates that
the properties of the superclassname class are extended to the classname class. This concept is known as
inheritance. Fields and methods are declared inside the body.

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

Rectangle R1 = new Rectangle();


Rectangle R2 =R1; /*Both R1 and R2 refer to the same object*/
Accessing Class Members:
The objects created had their own set of variables, we should assign values to these variables to
use them in our program.
The instance variables and methods can’t be accessed directly. They can be accessed with the
concerned objects, dot operator as shown below
objectname.variablename=value;
objectname.methodname (parameter-list);
Here objectname  name of the object
Variablename  name of the instance variable
methodname  name of the method that we wish to call
parameter-list  actual values that are separated by
Program:
class Rectangle
{
int length, width;
void getData(int x, int y)
{
length = x;
width=y;
}
int rectArea()
{
int area = length * width;
return (area);
}
}
Class Rectarea
{
public static void main(Sring args[])
{
Rectangle rect1=new Rectangle(15,10);
int area1=rect1.rectArea();
System.out.println(“Area 1:”+area1);
}
}
Output:
Area 1=150

How to initializing the instance variables:


It is the duty of the programmer to initialize the instance variables, depending on his requirements.
Example :
class Person
{
String name="Core";
int age=30;
void talk()
{
System.out.println("Hello Iam "+name);
System.out.println("My Age is "+age);
}
}
Class Demo
{
public static void main(String args[])
{
Person p1=new Person();
p1.name="Java";
p1.age=22;
p1.talk();
}
}
Output:
Hello Iam Core Java
My age is 22

Access Protection available in Java:


An Access Specifier is a keyword that specifies how to access the members of class or a class
itself. Java provides a few access specifiers for controlling the accessibility of the members of a class.
Access Specifier restricts the accessibility of the members to the other classes. Java support four types of
Visibility or Access Specifier are:
1. Public.
2. Private.
3. Protected.
4. Default.
(1). Public: A public means common to all. Public members of a class are accessible everywhere to
outside of the classes. So any other subclasses can read them and use them.
Syntax of Public: public class <Class_Name>
{
Class Definition
}
(2). Private: A private means within itself. Private members of a class are not accessible anywhere to
outside of the classes. They are accessible only within the class by the methods of that class.
Syntax of Private: private class <Class Name>
{
Class Definition
}
(3). Protected: Protected members of a class are accessible outside the class, but generally, within the
same directory or same package.
Syntax of Protected: protected class <Class Name>
{
Class Definition
}
(4). Default: If no access specifier is written by the programmer, then the java compiler users a „default‟
access specifier. Default members are accessible outside the class, but within the same directory.
Syntax of Default: class <Class Name>
{
Class Definition
}
What is Constructor? Explain Types of Constructors with an example in Java?
A constructor is a special member function of a class that has the same name as the class. A
constructor is called automatically when an object of the class is declared. Constructors are used
to initialize objects.
The constructor of a class is the first member function to be executed automatically when an
object of the class is created. The constructor is executed every time an object of that class
is defined. A Constructors is never called directly, instead it is invoked via the keyword “new”
operator. When we create an object of a class, all the instances variables must be initialized.
Rules of defining Constructors:
1. Constructors have the same name as the class name itself.
2. They do not specify a return type, not even void.
3. Constructors can accept parameters.
4. Constructors cannot be invoked explicitly.
5. A class can have more than one constructor.
6. Constructors takes arguments same as normal methods.
7. An Abstract class can have constructors.
8. An Interface should not have any constructors.
9. Constructors can use any access modifies, including private.
Types of Constructors: A Constructors of a class either 3 types.
1. Default Constructors.
2. Parameterized Constructors.
3. Copy Constructors.
1. Default Constructors: The Default Constructors is the Constructors which accept “Zero
Arguments” or “Without any parameters list”, and then we say „Default Constructors‟.
Example: class MyClass
{
int x, y, z;
MyClass() // Default Constructor.
{
X = 0;
Y = 0;
Z = 0;
}
}
In the above example Class Name is “MyClass” and Constructor Name is “MyClass” which
have the same name as Class Name and Constructor Name. Once the Constructor is defined, the
Constructor is automatically called immediately after the object is created, before the “new” operator
completes.

MyClass obj1 = new MyClass (); // Default Constructor


2. Parameterized Constructors: The Parameterized Constructor is the Constructor which accept “At
least one arguments” ten we say Parameterized Constructor.
Example: class MyClass
{
int x, y, z;
MyClass (int a, int b) // Parameterized Constructor.
{
x=a;
y=b;
}
}
Once the Constructor is defines, the Constructor is automatically called immediately after the
object is created, before the “new” operator completes.

MyClass obj2 = new MyClass (5, 10); // Parameterized Constructor.

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 specifiers (or) Visibility modes in java:


Java provides three types of visibility modifiers. public, private and protected. They provide
different levels of protection of data as given below
1. Public Access :
Any variable or method is visible to the entire class in which it is defined. We make them visible
to all the classes outside this class by declaring them as public.
E.g. public int number;
public void display();
A variable or method declared as public can be accessible everywhere throughout the program.
1. Friendly access :
When no access specifier is specified, the member of a class has "friendly" level. The difference
between the "Public" access and the "friendly" access is that the public modifier makes fields visible in
all classes, regardless of their packages. While the friendly access makes fields visible only in the same
package, but not in other packages.
2. Protected Access :
The protected modifier makes the fields visible to its subclasses in the same package and also to
the subclasses in other packages.
3. Private Access :
Private fields are accessible only with in their own class. They cannot be inherited by subclasses..
5. Private protected Access:
A field can be declared with two keywords private and protected together like private protected
int code

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

Other Class in same package. Yes Yes Yes No No


Sub Class in other package. Yes Yes No Yes No
Non-Sub Class in other package Yes No No No No
Inheritance

What is Inheritance explain in types of Inheritances with an example in Java?


Inheritance is a mechanism to derive a New Class from the Existing Class. Here Existing
Class is a Base class; New class is known as derived class.
(OR)
Inheritance is the property that allows “The reuse of an Existing Class to build a New Class”.
(OR)
Inheritance is the process of acquiring the qualities of one class to another class. These qualities
include both properties and action of the class. Using inheritances, we extend the features of a class
into another class.
Types of Inheritance:
Inheritance are mainly divided into 4 types there are
1. Single Inheritance. (Derived from only one Super Class)
2. Multilevel Inheritance. (One Super class, many sub classes)
3. Hierarchical Inheritance. (Derived from Derived Class)
4. Multiple Inheritances. (Derived from more than one Super Class)

1. Single Inheritance: Derivation of a class from only one super class is called single inheritance.

A Parent / Superclass / Base class

B
Child / Subclass / Derived class

2. Multilevel Inheritance: A Class is derived from another Derived Class it is called as


Multilevel Inheritances. A

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

Explain about Single Inheritance in Java?


Derivation of a class from only one super class is called single inheritance.
A Parent / Superclass / Base class

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

(Q) Explain about Multilevel Inheritance in Java?


A Class is derived from another Derived Class it is called as Multilevel Inheritances.
A
B

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
{

public static void main(String args[])


{
Percentage P1 = new Percentage(123,“ABC”,600,75);
P1.displayPercentage();
}
}
Save: MultiLevelInheritance.java
Compile: javac MultiLevelInheritance.java
Run: java MultiLevelInheritance
Output: Student Roll Number : 123
Student Name : ABC
Student Total Marks : 600
Percentage of Marks : 75
(Q) Explain about Hierarchical Inheritance in Java?
Deriving multiple classes based on the one Existing Class is called Hierarchical Inheritances.

B C D

Syntax of Hierarchical Inheritance:


class Superclass A
{
----------
----------
}
class SubClass B extends SuperClass A
{
----------
----------
}
class SubClass C extends SuperClass A
{
----------
----------
}

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.

Explain the Super keyword with an example in Java?


 If we create an object to super class, we can access only the super class members, but not the
sub class members.
 But if we create sub class object, all the members of both super and sub classes are available to it.
 Sometimes, the super class members and sub class members may have same names, in that
case by default only sub class members are accessible.
 This is the only reason; we always create an object to sub class in inheritances.
Using Super to call super class constructor: A subclass can call a constructor method of its
superclass by use of “super” keyword as below.
Syntax: super (parameter list);
 Super() must be used within a subclass constructor method.
 super() must always be the first statement executed inside a subclass constructor.

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

Output: Room Area = 50


Room Volume = 100

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

Circle Rectangle Triangle


Draw() Draw() 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:

Method Overloading Method Overriding


1. Write two or more methods with the same 1. Write two or more methods with the same
name but with different parameters lists is name and same parameters lists is called as
called as Method Overloading. Method Overloading.
2. Method Overloading is done in the same 2. Method Overriding is done in Super and Sub
class. Classes.
3. In Method Overloading, method return 3. In Method Overriding, method return type
type can be same or different. should be same.
4. Java Virtual Machine (JVM) decided 4. Java Virtual Machine (JVM) decided which
which method is called depending on the method is called depending on the data type
different in the methods. (class) of the object used to call the methods.
5. Method Overloading is code refinement. 5. Method Overriding is code replacement.
Same method is used to perform different Sub class method overrides the super class
task methods.
Operator Overloading
One operator can be used for different purposes, depending on the content. This concept is called
as Operator Overloading.
Consider the following example, here addition operation perform sum of two numbers. If the
operands of addition operator (+) is used for addition. The addition operator (+) will also give
concatenation of two strings.
Examples: - 10 + 2 = 12. // This is performing the Numerical values of addition.
Core + Java = Core Java // This is perform the String Concatenation.
Rules of Overloading Operators: - While representing the operators user has to follow certain rules.
1. Only Existing Operators can be overloaded.
2. We can’t change the basic meaning of the operators.
3. They are some operators that cannot be overloaded. They are ?, :, . etc.,
4. Binary Arithmetic Operators such as +, -, *, /, % must be explicitly returns a values. They must
be not attempting changes their own definitions.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy