Unit II Java
Unit II 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
}
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.
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.
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
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
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.
default
When we do not mention any access modifier, it is treated as default. It is
accessible only within same package.
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.
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.
Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide
Table for Access Modifier
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().
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.
Syntax:
interface {
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:
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.
For example,
class Person{
int age;
class Main{
p1.age = 31;
p2.age = 32;
}
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{
class Main{
p1.age = 30;
p2.age = 31;
Person.age = 32;
}
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.
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;
}
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.
class 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{
counter++;
class Main{
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.
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
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.
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);}
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Example:
/* 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();
class Test
{
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
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
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
Output:
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
In Java, we have 8 primitive data types. Java provides type wrappers, which are
classes that encapsulate a primitive type within an Object.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
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
There are two ways for converting a primitive type into an instance of the
corresponding wrapper class –
1. Using constrcutors
// 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 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.
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.
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.
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.
1. Static/Compile-Time Polymorphism
2. Dynamic/Runtime Polymorphism
Compile-Time Polymorphism
Runtime Polymorphism
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
// 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
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:
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
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.
The overloading functions always exist The overriding function always exists in
Scope
in the same scope different scope
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
Static
Can be overloaded Cannot be overridden
Methods
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.
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
Method Description
Here, the forName() method takes the name of the class to be reflected as
its argument.
2. Using getClass() method
Here, we are using the object of the Student class to create an object
of Class.
3. Using .class extension
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 {
}
class Main {
public static void main(String[] args) {
Name: Student
Modifier: public
Superclass: College
Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
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:
There are some predefined methods in enum classes that are readily
available for use.
ordinal(SMALL)
// returns 0
2. Enum compareTo()
Size.SMALL.compareTo(Size.MEDIUM)
// returns ordinal(SMALL) - ordinal(MEDIUM)
3. Enum toString()
SMALL.toString()
// returns "SMALL"
4. Enum name()
name(SMALL)
// returns "SMALL"
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.
package com.crunchify.tutorial;
this.value = value;
}}
}}}
Output:
Point-4
Enum constants are implicitly static and final and can not be changed once
created.
Point-5
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
Point-9
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
Point-14
Java inner class or nested class is a class that is declared inside the
class or interface.
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:
Type Description
Member Inner Class A class created within class and outside method.
Syntax
class Outer{
//code
class Inner{
//code
}
}
Example:
class Outer
{
class Inner
{
void msg()
{ System.out.println("data is "+data);}
}
in.msg();
}
Example:
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
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.
Syntax:
// Interface
interface Age {
int x = 21;
void getAge();
}
class Demo {
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.
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 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 = . . .;
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;
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.