[go: up one dir, main page]

0% found this document useful (0 votes)
4 views68 pages

Unit II Java

The document provides an overview of classes and objects in Java, explaining the concepts of identity, state, and behavior, as well as the syntax for creating classes and objects. It covers inheritance types, access modifiers, interfaces, static fields and methods, and constructors, detailing how they function and their significance in Java programming. Additionally, it includes examples to illustrate these concepts effectively.

Uploaded by

aswinrsgc
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)
4 views68 pages

Unit II Java

The document provides an overview of classes and objects in Java, explaining the concepts of identity, state, and behavior, as well as the syntax for creating classes and objects. It covers inheritance types, access modifiers, interfaces, static fields and methods, and constructors, detailing how they function and their significance in Java programming. Additionally, it includes examples to illustrate these concepts effectively.

Uploaded by

aswinrsgc
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/ 68

UNIT II

Classes and Objects


The class defines the blueprint of an object. Every class in java forms a new
data type. Once a class got created, we can generate as many objects as we
want. Every class defines the properties and behaviors of an object. All the
objects of a class have the same properties and behaviors that were defined in
the class.

Every class of java programming language has the following characteristics.

 Identity - It is the name given to the class.


 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.
 Look at the following picture to understand the class and object concept.

Behavior is encapsulated into methods (also known as functions) and


state (properties) is encapsulated in data called member variables.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains
properties as variables and behaviors as methods. Following is the syntax of class in
the java.

Syntax
class ClassName
{
data members declaration;
methods defination;
}
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the
class is said to be instantiated. All the objects that are created using a single class
have the same properties and methods. But the value of properties is different for
every object. Following is the syntax of class in the java.

Syntax
ClassName objectName = new ClassName( );

Inheritance
 Inheritance can be defined as the process of acquiring the properties of
parent’s class by child class.
 It provides the mechanism of code re-usability and represents IS-A
relationship.
 extends keyword is used for inheritance.

Syntax:
class Base
{
// code
}
class Derive extends Base
{
// code
}

Example: Sample program for inheritance


class A
{
int result;
public void square(int a)
{
result = a * a;
System.out.println("The square of the "+a+" is: "+result);
}
}
public class B extends A
{
public void cube(int a)
{
result = a * a * a;
System.out.println("The cube of the "+a+" is: "+result);
}
public static void main(String args[])
{
int a = 25;
B obj = new B();
obj.square(a);
obj.cube(a);
}
}
Output:
The square of the 25 is: 625
The cube of the 25 is: 15625

Types of inheritance
There are three types of inheritance in Java.
1. Single level
2. Multilevel inheritance
3. Hierarchical

4.Hybrid
Single Level Inheritance
When a class extends only one class, then it is called single level inheritance.

Fig: Single Level Inheritance

Syntax:
class A
{
//code
}
class B extends A
{
//code
}
Example:
class Parent
{
public void m1()
{
System.out.println("Class Parent method");
}
}
public class Child extends Parent
{
public void m2()
{
System.out.println("Class Child method");
}
public static void main(String args[])
{
Child obj = new Child();
obj.m1();
obj.m2();
}
}

Multilevel Inheritance
Multilevel inheritance is a mechanism where one class can be inherited from
a derived class thereby making the derived class the base class for the new
class.

Fig: Multilevel Inheritance

Syntax:

class A
{
//code
}
class B extends A
{
//code
}
class C extends B
{
//code
}
Example: Sample program for multilevel inheritance

class A
{
public void m1()
{
System.out.println("Class A method");
}
}
class B extends A
{
public void m2()
{
System.out.println("Class B method");
}
}
class C extends B
{
public void m3()
{
System.out.println("Class C method");
}
public static void main(String args[])
{
C obj = new C();
obj.m1();
obj.m2();
obj.m3();
}
}

Hierarchical Inheritance
When one base class can be inherited by more than one class, then it is
called hierarchical inheritance.
Fig: Hierarchical Inheritance

Syntax:

class A
{
// code
}
class B extends A
{
// code
}
class C extends A
{
//code
}
Example: Sample program for hierarchical inheritance
class A
{
public void m1()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void m2()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void m3()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void m4()
{
System.out.println("method of Class D");
}
}
public class MainClass
{
public void m5()
{
System.out.println("method of Class MainClass");
}
public static void main(String args[])
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
D obj4 = new D();
obj1.m1();
obj2.m1();
obj3.m1();
obj4.m1();
}
}

Output:
method of Class A
method of Class A
method of Class A
method of Class A

Hybrid Inheritance in java


The hybrid inheritance is the combination of more than one type of inheritance.

Multiple Inheritances

 In multiple inheritance, one derive class can extend more than one base
class.
 Multiple inheritances are basically not supported by Java, because it
increases the complexity of the code.
 But they can be achieved by using interfaces.
Fig: Multiple Inheritance

Types of access modifier


There are 4 types of access modifiers available in Java.

 public
 default
 protected
 private

public
The member with public modifiers can be accessed by any classes. The public
methods, variables or class have the widest scope.

Example: Sample program for public access modifier

public static void main(String args[])


{
// code
}

default
When we do not mention any access modifier, it is treated as default. It is
accessible only within same package.

Example: Sample program for default access modifier

int a = 25;
String str = "Java";
boolean m1()
{
return true;
}

protected
The protected modifier is used within same package. It lies between public
and default access modifier. It can be accessed outside the package but
through inheritance only.
A class cannot be protected.

Example: Sample program for protected access modifier

class Employee
{
protected int id = 101;
protected String name = "Jack";
}
public class ProtectedDemo extends Employee
{
private String dept = "Networking";
public void display()
{
System.out.println("Employee Id : "+id);
System.out.println("Employee name : "+name);
System.out.println("Employee Department : "+dept);
}
public static void main(String args[])
{
ProtectedDemo pd = new ProtectedDemo();
pd.display();
}
}

Output:
Employee Id : 101
Employee name : Jack
Employee Department : Networking

private
The private methods, variables and constructor are not accessible to any
other class. It is the most restrictive access modifier. A class except a nested
class cannot be private.

Example: Sample program for private access modifier

public class PrivateDemo


{
private int a = 101;
private String s = "TutorialRide";
public void show()
{
System.out.println("Private int a = "+a+"\nString s = "+s);
}
public static void main(String args[])
{
PrivateDemo pd = new PrivateDemo();
pd.show();
System.out.println(pd.a+" "+pd.s);
}
}

Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide
Table for Access Modifier

The super keyword in Java

 super keyword is similar to this keyword in Java.


 It is used to refer to the immediate parent class of the object.
Use of super keyword in Java

 super () calls the parent class constructor with no argument.


 super.methodname calls method from parents class.
 It is used to call the parents class variable.

Interface
Java does not support multiple inheritance. Multiple inheritance means a class derived
from more than one direct super class. This increases complexities and ambiguity in
the relationship among classes. The problem is clearly visible if we consider what
happens in function overriding. Suppose there are two classes, A and B, each defining
a function called func(). Now, let’s say we define another class, C, which inherits both
from A and B (multiple inheritance), but let’s say this class does not override the
function called func().

Now, if we do something like the following:

C c = new C();

c.func();
Can we determine which member function func() is invoked? Is it function defined by
class A or class B? As we can see, the class C inherits this function doubly from both
A and B. This creates ambiguity and the compiler is in a fix to resolve the issue.

An Interface in Java programming language is defined as an abstract type used to


specify the behavior of a class. An interface in Java is a blueprint of a class. A Java
interface contains static constants and abstract methods. The interface in Java
is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not the method body. It is used to achieve abstraction and multiple
inheritance in Java. In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.

Syntax:

interface {

// declare constant fields


// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword. It is used to provide total
abstraction. That means all the methods in an interface are declared with an
empty body and are public and all fields are public, static, and final by
default. A class that implements an interface must implement all the methods
declared in the interface. To implement interface use implements keyword.
Why do we use an Interface?

 It is used to achieve total abstraction.


 Since java does not support multiple inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in
the interface are final, public and static.

We can implement more than one interfaces in our program because that
doesn’t cause any ambiguity(see the explanation below).

// A simple interface

interface Player
{
final int id = 10;
int move();
}

Example:

interface X
{
public void myMethod();
}
interface Y
{
public void myMethod();
}
class JavaExample implements X, Y
{
public void myMethod()
{
System.out.println("Implementing more than one
interfaces");
}
public static void main(String args[])
{
JavaExample obj = new JavaExample();
obj.myMethod();
}
}

Output:

Implementing more than one interfaces

As you can see that the class implemented two interfaces. A class can
implement any number of interfaces. In this case there is no ambiguity even
though both the interfaces are having same method. Why? Because methods in
an interface are always abstract by default, which doesn’t let them give their
implementation (or method definition ) in interface itself.

Static Fields and Methods


The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes.

1) Java static variable


o If you declare any variable as static, it is known as a static variable. The static
variable gets memory only once in the class area at the time of class loading.
When you create an object or instance for a class in Java, each object will have its own copy
of the members such as variables and methods.

For example,

class Person{

int age;

class Main{

public static void main(String args[]){

Person p1 = new Person();

Person p2 = new Person();

p1.age = 31;

p2.age = 32;

System.out.println("P1\'s age is: " + p1.age);

System.out.println("P2\'s age is: " + p2.age);

}
In the above example, both the person objects p1 and p2 have their own local copy of the
non-static variable age. If you change them, they will store different values then.

However, if the same variable age would have been declared as a static variable, then all the
objects declared for this class would share the same copy of the static variable. This is so
because of static variables or for that matter, all the static members are not associated with
instances, but with classes. Hence, you won’t even have to create an object to access static
members. Consider the same example but with a static variable called age.

class Person{

static int age;

class Main{

public static void main(String args[]){

Person p1 = new Person();

Person p2 = new Person();

p1.age = 30;

p2.age = 31;

Person.age = 32;

System.out.println("P1\'s age is: " + p1.age);

System.out.println("P2\'s age is: " + p2.age);

}
2) Java static method
If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.

It is common to often refer to static methods in Java as class methods. The


reason being that the static members are associated with the classes and with
their objects. Similar to static variables, static methods can also be invoked
using the class name. There are some important points that you need to consider
when you work with static methods in Java. These are -

1. The static methods of a particular class can only access the static variables
and can change them.
2. A static method can only call other static methods.
3. Static methods can’t refer to non-static variables or methods.
4. Static methods can’t refer to ―super‖ or ―this‖ members.
Also, often you will notice that the main method in Java is defined as static.
This is so because you don’t need an object to call the main method in Java. If
you have defined the main method in Java as non-static, then the Java Virtual
Machine (JVM) would have first created an instance for the main class and then
called the main method using that instance which would lead to unnecessary
memory usage. Moreover, there are tons of static methods defined in the
Wrapper Classes and Utility Classes in Java.
//Java Program to get the cube of a given number using the 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);
}
}

Restrictions for the 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.

Next, consider the below example.

class Test{
int counter;
public static void increment(){
counter++;
System.out.println("Current value of Counter is: " + counter);
}
}
class Main{
public static void main(String args[]){
Test.increment();
}
}

The above program will generate an error. This is so because it has tried to access a
non-static variable called counter inside a static method called increment().

Example 2:

class Test{

static int counter;

public static void increment(){

counter++;

System.out.println("Current value of Counter is: " + counter);

class Main{

public static void main(String args[]){


Test.increment();

Test.increment();

Test.increment();

Constructor
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for
the object is allocated in the memory. It is a special type of method which is used to
initialize the object. Every time an object is created using the new() keyword, at
least one constructor is called.

Note: It is not necessary to write a constructor for a class. It is because java


compiler creates a default constructor if your class doesn’t have any.

How Constructors are Different From Methods in Java?


 Constructors must have the same name as the class within which it is defined
while it is not necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type
or void if does not return any value.
 Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.
 A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


class_name()
{
}

Example
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example:
//Java Program to demonstrate the use of the parameterized constructor.
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

 super can be used to refer immediate parent class instance variable.


 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

Example:

/* Base class Person */


class Person
{
void message()
{
System.out.println("This is person class");
}
}

/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
void display()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method


super.message();
}
}

class Test
{
public static void main(String args[])
{
Student s = new Student();

s.display();
}
}

Cosmic Superclass in Java


In Java, the Object class is the parent class of all the Java classes. Every Java
class is a direct or indirect child of the Java Object class. Hence, every Java
class extends the Object class. Therefore, we need not to write the following
statement to inherit the class.

class Student extends Object

The subclass internally inherits all the methods of the Object class. Hence, we
can say that the Object class is the cosmic superclass in Java. The class
belongs to java.lang package.
The four most important methods of the cosmic superclass (Object class) are as
follows:

Methods Description

String toString() It returns a string representation of the object.

boolean It checks the equality of objects. Note that the method


equals(Object does not compare the content of two objects instead it
obj) compares the references of two variables.

Object clone() It creates a copy of an object.

int hashCode() It returns an integer from the entire integer range.

Example I:
public class ObjectComparison
{
public static void main(String args[])
{
//creating constructor of the String class
String str1 = new String("javatpt");
//creating constructor of the String class
String str2 = new String("java");
String str3 = new String("java");
//invoking the equals() method
System.out.println(str1.equals(str2)); //objects are not equal
System.out.println(str2.equals(str1)); //objects are not equal
System.out.println(str2.equals(str3)); //objects are equal
}
}

Output:

false
false
true

In the above program, observe that we have not extended the Java Object class
but used the equals() method of the Object class.

Example II

public class ToStringExample


{
static int a = 60, b=90;
int c;
//creating a constructor of the class
ToStringExample()
{
System.out.println("The sum of integers is: ");
c=a+b;
System.out.println("The sum is: "+c);
}

public static void main(String args[])


{
ToStringExample obj = new ToStringExample();
System.out.println(obj.toString());
} }

Output:

The sum of integers is:


The sum is: 150
ToStringExample@490d6c15

In the above example also, we have used the toString() method of the Object
class without extending the class. Therefore, the Java Object class is known as a
cosmic superclass.

• The Object.toString() method prints class name and the hash code
of the object

Wrapper Classes, Autoboxing and Unboxing

Java Wrapper Classes

In Java, we have 8 primitive data types. Java provides type wrappers, which are
classes that encapsulate a primitive type within an Object.

 A wrapper class wraps (encloses) around a primitive datatype and gives it an


object appearance. Wherever the primitive datatype is required as an object
type, this type wrapper can be used.
 Wrapper classes include methods to unwrap the object and give back the
data type.

 The type wrappers classes are part of java.lang package.

 Each primitive type has a corresponding wrapper class.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float
double Double

When to use Wrapper Classes

Java wrapper classes are used in scenarios –

 When two methods wants to refer to the same instance of an primitive type,
then pass wrapper class as method arguments.

 Java Generics works only with object types and does not support primitive
types.

 Java Collections deal only with objects; to store a primitive type in one of
these classes, you need to wrap the primitive type in a class.

 When you want to refer null from data type, the you need object. Primitives
cannot have null as value.

Conversions

Converting Primitive Types to Wrapper Classes

There are two ways for converting a primitive type into an instance of the
corresponding wrapper class –

1. Using constrcutors

2. Using static factory methods

// 1. using constructor
Integer object = new Integer(10);
// 2. using static factory method
Integer anotherObject = Integer.valueOf(10);

In the above example, the valueOf() method is a static factory method that returns
an instance of Integer class representing the specified int value. Similarly, we can
convert the other primitive types
like boolean to Boolean, char to Character, short to Short, etc.

Converting Wrapper Class to Primitive Type

Converting from wrapper class to primitive type is simple. We can use the
corresponding instance methods to get the primitive type.
e.g. intValue(), doubleValue(), shortValue() etc.

Integer object = new Integer(10);

int val = object.intValue(); //wrapper to primitive

Autoboxing and Unboxing

Beginning with JDK 5, Java added two important features:

 Autoboxing
 Auto-Unboxing

Autoboxing
Autoboxing is the automatic conversion of the primitive types into their
corresponding wrapper class. The automatic conversion of primitive data type
into its corresponding wrapper class is known as autoboxing, for example, byte
to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects. For example, converting an int to an Integer,
a char to a Character, and so on.

Wrapper class Example: Primitive to Wrapper(Auto boxing)

//Java program to convert primitive into objects


//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer j=a;//autoboxing, now compiler will do internally

System.out.println(a+" "+" "+j);


}}

Output:

20 20
Unboxing
The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing. Since Java 5, we do not need to use the intValue()
method of wrapper classes to convert the wrapper type into
primitives.

Wrapper class Example: Wrapper to Primitive(Unboxing)

//Java program to convert object into primitives


//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3); //Boxing
int j=a;//unboxing, now compiler will do internally

System.out.println(a+" "+" "+j);


}}

Output:

33
Polymorphism in Java
Polymorphism is the ability of an object to take on different forms. In Java,
polymorphism refers to the ability of a class to provide different implementations of a
method, depending on the type of object that is passed to the method.

To put it simply, polymorphism in Java allows us to perform the same action in many
different ways. Any Java object that can pass more than one IS-A test is polymorphic in
Java. Therefore, all the Java objects are polymorphic as it has passed the IS-A test for
their own type and for the class Object.

Also, Polymorphism in Java can be classified into two types, i.e:

1. Static/Compile-Time Polymorphism

2. Dynamic/Runtime Polymorphism

Compile-Time Polymorphism

Compile Time Polymorphism In Java is also known as Static


Polymorphism. Furthermore, the call to the method is resolved at compile-time.
Compile-Time polymorphism is achieved through Method Overloading. This type of
polymorphism can also be achieved through Operator Overloading. However, Java does
not support Operator Overloading.

Runtime Polymorphism

Runtime polymorphism in Java is also popularly known as Dynamic Binding or


Dynamic Method Dispatch. In this process, the call to an overridden method is resolved
dynamically at runtime rather than at compile-time. You can achieve Runtime
polymorphism via Method Overriding.

Method Overriding is done when a child or a subclass has a method with the same name,
parameters, and return type as the parent or the superclass; then that function overrides
the function in the superclass. In simpler terms, if the subclass provides its definition to a
method already present in the superclass; then that function in the base class is said to be
overridden.

Types of Polymorphism
You can perform Polymorphism in Java via two different methods:

1. Method Overloading
2. Method Overriding

Method overloading
Method overloading is the process that can create multiple methods of the same name in
the same class, and all the methods work in different ways. Method overloading occurs
when there is more than one method of the same name in the class.

Method Overloading is when a class has multiple methods with the same name, but the
number, types, and order of parameters and the return type of the methods are different.
Java allows the user freedom to use the same name for various functions as long as it can
distinguish between them by the type and number of parameters.
Example of Method Overloading in Java
class Shapes {
public void area()
{
System.out.println("Find area ");
}
public void area(int r)
{
System.out.println("Circle area = "+3.14*r*r);
}
public void area(double b, double h)
{
System.out.println("Triangle area="+0.5*b*h);
}
public void area(int l, int b)
{
System.out.println("Rectangle area="+l*b);
}
}
class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object

myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);

}}

Output:

Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12
Method Overloading Rules
There are some rules which you need to follow for implementing Method
Overloading

Rule 1: Change the method signature


The most important rule for method overloading in Java is to change the
method signature. The method signature means a number of parameters,
types of parameters and the sequence of parameters. At least one of them
should be different in order to overload a method.

Rule 2: Do not consider the Return type of method as a part


of the method signature.
Never consider that changing only the return type of the method, the
method can be overloaded because the return type is not part of the method
signature.
public class MyClass
{
// Overloaded method
public int multiply(int num1, num2)
{
return num1 * num2;
}

// Overloading method
public float multiply(int num1, num2) //Not valid because we only changed the return
type
{
return num1 * num2;
}
}
Rule 3: The type of exceptions thrown from the methods are
also not considered while overloading a method.
public class MyClass
{
// Overloaded method
public int multiply(int num1, num2) throws NullPointerException
{
return num1 * num2;
}
// Overloading method

public int multiply(int num1, num2) throws Exception


//not valid because throwing different type of exception will not lead to method
overloadig
{
return num1 * num2;
}
}

Method Overriding
During inheritance in Java, if the same method is present in both the superclass
and the subclass. Then, the method in the subclass overrides the same method in
the superclass. This is called method overriding. Method overriding is the
process when the subclass or a child class has the same method as declared in
the parent class.
Example of Method Overriding
class Vehicle{
void run()
{
System.out.println("Vehicle is moving");}
}
class Car2 extends Vehicle
{ //defining the same method as in the parent class
void run()
{
System.out.println("car is running safely");
}
public static void main(String args[]){
Car2 obj = new Car2();//creating object
obj.run();//calling method
}
}
Output:

Car is running safely

Overloading vs Overriding in Java


Basis Method Overloading Method Overriding

Method overloading is when two or


Method overriding is when a subclass modifies a
Definition more methods have the same name
method of superclass having the same signature
and different arguments

The overloaded methods must have The overridden methods must have the same
Method different method signatures. It means method signature. It means that method name,
Signature that the methods must differ in at least number of arguments, order of arguments, and
one of these: number of parameters, type of arguments should be an exact match
Basis Method Overloading Method Overriding

type of parameters, and order of


parameters, but should have the same
name

If the base class method has a primitive data


type, then the overridden method of the
The return type of overloaded methods subclass must have the same data type.But if
Return Type may or may not have the same return the base class method has a derived return
type type, then the overridden method of the
subclass must have either the same data type or
subclass of the derived data type.

We do not have any restriction on


Access access modifiers and may use any The overridden method in subclass should have
Modifier access modifier in the overloaded the same or less restricted access modifier
method

The method call is binded to method The method call is binded to method definition
Binding definition at compile time. Also known at compile time. Also known as Dynamic
as Static Binding. Binding.

Polymorphism It is an application of compile-time


It is an application of run-time polymorphism
Type polymorphism

The overloading functions always exist The overriding function always exists in
Scope
in the same scope different scope

Gives functionality to allow different


Gives functionality to add some extra or
methods to have the same name and
Purpose unexpected functionality in the subclass as
act differently based on the parameters
compared to the superclass
supplied to them

Inheritance Doesn't need inheritance, can be Relies on inheritance, occurs in classes depicting
Scope performed within the same class is-a (parent-child) relationship

Private
Can be overloaded Cannot be overridden
Methods

Final Methods Can be overloaded Cannot be overridden

Static
Can be overloaded Cannot be overridden
Methods

If overloading breaks, we get a compile- If overriding breaks, we get run-time errors


Error Handling
time error which is relatively easy to fix which are more serious and relatively more
Basis Method Overloading Method Overriding

complex to fix.

We can overload methods any number We can override a method only one time in an
Usage
of times in a class inheriting class

Reflection in Java
Java Reflection is the process of analyzing and modifying all the capabilities of a class at
runtime. Reflection API in Java is used to manipulate class and its members which include
fields, methods, constructor, etc. at runtime.

Reflection in Java is an API(Application Programming Interface) that is used at


runtime to analyze or change classes, methods, and interfaces. It is a process of
examining or modifying the run time behavior of a class at run time.

The java.lang.Class is a class that provides many methods that we can use to get
metadata of the class and to examine and change the runtime behavior of a class.
There are two packages- java.lang and java.lang.reflect that provide classes for
Java Reflection.

One advantage of reflection API in Java is, it can manipulate private members of the class
too.Java Reflection is a process of examining or modifying the run time behavior of a class
at run time. The java.lang.Class class provides many methods that can be used to get
metadata, examine and change the run time behavior of a class.

The java.lang and java.lang.reflect packages provide classes for java reflection.
Reflecting Fields, Methods, and Constructors
The package java.lang.reflect provides classes that can be used for manipulating class
members. For example,
 Method class - provides information about methods in a class
 Field class - provides information about fields in a class
 Constructor class - provides information about constructors in a class

Following is a list of various Java classes in java.lang.package to implement


reflection-

 Field: This class is used to gather declarative information such as datatype,


access modifier, name and value of a variable.
 Method: This class is used to gather declarative information such as access
modifier, return type, name, parameter types and exception type of a
method.
 Constructor: This class is used to gather declarative information such as
access modifier, name and parameter types of a constructor.
 Modifier: This class is used to gather information about a particular access
modifier.

Methods used in java.lang.Class


The java.lang.The class performs two essential tasks:

 It provides methods to get the metadata of a class at runtime.


 It provides methods to examine and change the behavior of the class at
runtime.
Commonly used methods of the Class class:

 Public String getName (): Returns the name of the class.


 public Class getSuperclass(): Returns the super class reference
 Public Class[] getInterfaces() : Returns an array of interfaces implemented
by the specified class
 Public in getModifiers (): Returns an integer value representing the
modifiers of the specified class which needs to be passed as a parameter to
―public static String toString (int i )” method which returns the access
specifier for the given class.

Method Description

public String getName() returns the name of the class.

This method loads the class and returns the


public static Class forName(String className)
reference of Class.

public Object newInstance() It creates a new object of the class.

public boolean isInterface() This method checks if it is an interface.

public boolean isArray() This method checks if it is an array.

public boolean isPrimitive() This method checks if it is primitive.

It returns the superclass or parent class


public Class getSuperclass()
reference.

It returns the total number of fields in the


public Field[] getDeclaredFields()
class.

It returns the total number of methods of the


public Method[] getDeclaredMethods()
class.

public Method getDeclaredMethod(String name,Class[]


This method returns the method class instance.
parameterTypes)

It returns the total number of constructors of


public Constructor[] getDeclaredConstructors()
this class.
How to get the object of Class class?

 In order to reflect a Java class, we first need to create an object of Class.


 And, using the object we can call various methods to get information
about methods, fields, and constructors present in a class.
 There exists three ways to create objects of Class:
 1. Using forName() method

 class Student {...}


 // create object of Class


 // to reflect the Student class
 Class a = Class.forName("Student");

 Here, the forName() method takes the name of the class to be reflected as
its argument.
 2. Using getClass() method

 // create an object of Student class


 Student d1 = new Student();

 // create an object of Class


 // to reflect Student
 Class b = d1.getClass();

 Here, we are using the object of the Student class to create an object
of Class.
 3. Using .class extension

 // create an object of Class


 // to reflect the Student class
 Class c = Student.class;

 Now that we know how we can create objects of the Class. We can use
this object to get information about the corresponding class at runtime.
Example:
import java.lang.Class;
import java.lang.reflect.*;

class College {
}

public class Student extends College {


public void display() {
System.out.println("I am a student.");
}
}

class Main {
public static void main(String[] args) {

Student d1 = new Student ();// create an object of student

Class obj = d1.getClass();// create an object of Class


// using getClass()

String name = obj.getName();// get name of the class


System.out.println("Name: " + name);

// get the access modifier of the class


int modifier = obj.getModifiers();

// convert the access modifier to string


String mod = Modifier.toString(modifier);
System.out.println("Modifier: " + mod);

// get the superclass of Student


Class superClass = obj.getSuperclass();
System.out.println("Superclass: " + superClass.getName());
}
}
Output

Name: Student
Modifier: public
Superclass: College

Pros and Cons of Reflection


ros: Inspection of interfaces, classes, methods, and fields during runtime is
possible using reflection, even without using their names during the compile
time. It is also possible to call methods, instantiate a clear or to set the value of
fields using reflection. It helps in the creation of Visual Development
Environments and class browsers which provides aid to the developers to write
the correct code.

Cons: Using reflection, one can break the principles of encapsulation. It is


possible to access the private methods and fields of a class using reflection.
Thus, reflection may leak important data to the outside world, which is
dangerous. For example, if one access the private members of a class and sets
null value to it, then the other user of the same class can get the
NullReferenceException, and this behaviour is not expected.

Another demerit is the overhead in performance. Since the types in reflection


are resolved dynamically, JVM (Java Virtual Machine) optimization cannot take
place. Therefore, the operations performed by reflections are usually slow.

Because of the above-mentioned cons, it is generally advisable to avoid using


reflection. It is an advanced feature that should only be used by programmers or
developers who have a good knowledge of the basics of the language. Always
remember! Whenever reflection is used, the security of the application is
compromised.

Java Enums
The Enum in Java is a data type which contains a fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) , directions
(NORTH, SOUTH, EAST, and WEST), season (SPRING, SUMMER,
WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN,
WHITE, and BLACK) etc. According to the Java naming conventions, we
should have all constants in capital letters. So, we have enum constants in
capital letters.

Java Enums can be thought of as classes which have a fixed set of constants (a
variable that does not change). The Java enum constants are static and final
implicitly. It is available since JDK 1.5. Enums are used to create our own data
type like classes. The enum data type (also known as Enumerated Data Type) is
used to define an enum in Java. Unlike C/C++, enum in Java is more powerful.
Here, we can define an enum either inside the class or outside the class.
Example:

Methods of Java Enum Class

There are some predefined methods in enum classes that are readily
available for use.

1. Java Enum ordinal()

The ordinal() method returns the position of an enum constant. For


example,

ordinal(SMALL)
// returns 0

2. Enum compareTo()

The compareTo() method compares the enum constants based on


their ordinal value. For example,

Size.SMALL.compareTo(Size.MEDIUM)
// returns ordinal(SMALL) - ordinal(MEDIUM)

3. Enum toString()

The toString() method returns the string representation of the enum


constants. For example,

SMALL.toString()
// returns "SMALL"

4. Enum name()

The name() method returns the defined name of an enum constant in


string form. The returned value from the name() method is final. For
example,

name(SMALL)
// returns "SMALL"

5. Java Enum valueOf()

The valueOf() method takes a string and returns an enum constant


having the same string name. For example,
Size.valueOf("SMALL")
// returns constant SMALL.

Some very important points on Java Enum:

Point-1

All enums implicitly extend java.lang.Enum. Since Java does not support
multiple inheritance, an enum cannot extend anything else.

Point-2

Enum in Java are type-safe: Enum has there own name-space. It means your
enum will have a type for example ―Company‖ in below example and you can
not assign any value other than specified in Enum Constants.

public enum Company {

EBAY, PAYPAL, GOOGLE, YAHOO, ATT

Company cName = Company.EBAY;

cName = 1; // Compilation Error


Point-3

You can specify values of enum constants at the creation


time. MyEnum.values() returns an array of MyEnum’s values.

package com.crunchify.tutorial;

public class CrunchifyEnumExample {

public enum Company {

EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);

private int value;

private Company(int value) {

this.value = value;

}}

public static void main(String[] args) {

for (Company cName : Company.values()) {

System.out.println("Company Value: " + cName.value + " -


Company Name: " + cName);

}}}

Output:

Company Value: 30 - Company Name: EBAY

Company Value: 10 - Company Name: PAYPAL


Company Value: 15 - Company Name: GOOGLE

Company Value: 20 - Company Name: YAHOO

Company Value: 25 - Company Name: ATT

Point-4

Enum constants are implicitly static and final and can not be changed once
created.

Point-5

Enum can be safely compare using:

1. Switch-Case Statement
2. == Operator
3. .equals() method

Point-6

You can not create instance of enums by using new operator in Java because
constructor of Enum in Java can only be private and Enums constants can only
be created inside Enums itself.

Point-7

Instance of Enum in Java is created when any Enum constants are first called
or referenced in code.
Point-8

An enum specifies a list of constant values assigned to a type.

Point-9

An enum can be declared outside or inside a class, but NOT in a method.

Point-10
An enum declared outside a class must NOT be marked static, final , abstract,
protected , or private

Point-11
Enums can contain constructors, methods, variables, and constant class bodies.

Point-12

enum constants can send arguments to the enum constructor, using the syntax
BIG(8), where the int literal 8 is passed to the enum constructor.

Point-13

enum constructors can have arguments, and can be overloaded.

Point-14

enum constructors can NEVER be invoked directly in code. They are


always called automatically when an enum is initialized.
Point-15

The semicolon at the end of an enum declaration is optional.

These are legal:

 enum Foo { ONE, TWO, THREE}


 enum Foo { ONE, TWO, THREE};

Inner Classes (Nested Classes)

Java inner class or nested class is a class that is declared inside the
class or interface.

We use inner classes to logically group classes and interfaces in one


place to be more readable and maintainable.

Additionally, it can access all the members of the 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 three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it can access


all the members (data members and methods) of the outer
class, including private.
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.

Types of Nested classes


There are two types of nested classes non-static and static nested classes. The
non-static nested classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Type Description

Member Inner Class A class created within class and outside method.

Anonymous Inner Class A class created for implementing an interface or extending


class. The java compiler decides its name.

Local Inner Class A class was created within the method.


Static Nested Class A static class was created within the class.

Member Inner class


A non-static class that is created inside a class but outside a method is
called member inner class. It is also known as a regular inner class. It can be
declared with access modifiers like public, default, private, and protected.

Syntax

class Outer{
//code
class Inner{
//code
}
}
Example:

class Outer
{

private int data=30;

class Inner
{

void msg()
{ System.out.println("data is "+data);}
}

public static void main(String args[]){

Outer obj=new Outer();


Outer.Inner in=obj.new Inner();

in.msg();
}

Local inner class


A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block. Generally,
this block is a method body. Sometimes this block can be a for loop, or an if
clause. Local Inner classes are not a member of any enclosing classes. They
belong to the block they are defined within, due to which local inner classes
cannot have any access modifiers associated with them. However, they can be
marked as final or abstract. These classes have access to the fields of the class
enclosing it.

Example:

public class Outer


{
private int data=30;//instance variable

void display()
{
class Inner
{
void msg()
{
System.out.println(data);
}
}
Inner l=new Inner();
l.msg();
}
public static void main(String args[]){
Outer obj=new Outer();
obj.display();
}
}

Output:

00:00/04:58

30

Anonymous Inner Class

It is an inner class without a name and for which only a single object is
created. An anonymous inner class can be useful when making an instance
of an object with certain “extras” such as overriding methods of a class or
interface, without having to actually subclass a class.

Anonymous inner class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Syntax:

// Test can be interface,abstract/concrete class


Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};
 A normal class can implement any number of interfaces but the
anonymous inner class can implement only one interface at a time.
 A regular class can extend a class and implement any number of
interfaces simultaneously. But anonymous Inner class can extend a class
or can implement an interface but not both at a time.
 For regular/normal class, we can write any number of constructors but we
can’t write any constructor for anonymous Inner class because the
anonymous class does not have any name and while defining constructor
class name and constructor name must be same.
Example:

// Interface
interface Age {
int x = 21;
void getAge();
}

class Demo {

public static void main(String[] args)


{

// Myclass is hidden inner class of Age interface


// whose name is not written but an object to it
// is created.
Age oj1 = new Age() {

@Override public void getAge()


{
// printing age
System.out.print("Age is " + x);
}
};

oj1.getAge();
}
}

Output
Age is 21

A class is created, but its name is decided by the compiler, which extends
the Age interface and provides the implementation of the getAge()
method.

Java static nested class


A static class is a class that is created inside a class, is called a static nested
class in Java. It cannot access non-static data members and methods. It can be
accessed by outer class name.

o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members o

Example:

public class TestOuter2


{

static int data=30;

static class Inner


{

static void msg(){System.out.println("data is "+data);}

}
public static void main(String args[])

{
TestOuter2.Inner.msg();//no need to create the instance of static nested

class

}
}

Output:

data is 30

Java Generics
In many programming languages—in particular, in C—you have to fix the sizes
of all arrays at compile time. Programmers hate this because it forces them into
uncomfortable trade-offs. How many employees will be in a department? Surely
no more than 100. What if there is a humongous department with 150
employees? Do we want to waste 90 entries for every department with just 10
employees?

In Java, the situation is much better. You can set the size of an array at runtime.

int actualSize = . . .;

Employee[] staff = new Employee[actualSize];


Of course, this code does not completely solve the problem of dynamically
modifying arrays at runtime. Once you set the array size, you cannot change it
easily. Instead, the easiest way in Java to deal with this common situation is to
use another Java class, called ArrayList. The ArrayList class is similar to an
array, but it automatically adjusts its capacity as you add and remove elements,
without your needing to write any code.
As of Java SE 5.0, ArrayList is a generic class with a type parameter. To
specify the type of the element objects that the array list holds, you append a
class name enclosed in angle brackets, such as ArrayList<Employee>. Here we
declare and construct an array list that holds Employee objects:

ArrayList<string> staff = new ArrayList<string>();

The array list manages an internal array of object references. Eventually, that
array will run out of space. This is where array lists work their magic: If you
call add and the internal array is full, the array list automatically creates a bigger
array and copies all the objects from the smaller to the bigger array.

import java.util.ArrayList;

public class J5Example {


public static void main(String[] args) {
// Create an ArrayList.
// This list only allows elements of type String.
ArrayList<String> userNames = new ArrayList<String>();
// Add string to list
userNames.add("tom");
userNames.add("jerry");

String userName1 = userNames.get(0);


System.out.println("userName1 = " + userName1);
}
}

In the above example, with the help of Generics, you can create
an ArrayList object which only allows to contain elements with type of String, and
not allows to contain elements with other types.

Parameter Passing Techniques in Java


1. Pass By Value: Changes made to formal parameter do not get transmitted back to
the caller. Any modifications to the formal parameter variable inside the called
function or method affect only the separate storage location and will not be reflected
in the actual parameter in the calling environment. This method is also called as call
by value.
Output:
Value of a: 10 & b: 20
Value of a: 10 & b: 20

2.Call by reference(aliasing): Changes made to formal parameter


do get transmitted back to the caller through parameter passing. Any
changes to the formal parameter are reflected in the actual parameter
in the calling environment as formal parameter receives a reference
(or pointer) to the actual data. This method is also called as call by
reference. This method is efficient in both time and space.
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
Please note that when we pass a reference, a new reference variable to
the same object is created. So we can only change members of the object
whose reference is passed

You might also like