You are on page 1of 33

Java

Class, Object, Access modifier, final Keyword, Polymorphism, Inner


Class
Class in Java
• A class is a group of objects that has common properties. It is a template or
blueprint from which objects are created.
• A class in java can contain:
data member
method
block
class and interface

• Syntax to declare a class

class <class_name>{
data member;
method;
}

2
Object in Java
• An entity that has state and behaviour is known as an object e.g. chair, bike,
marker, pen, table, car etc.
• It can be physical or logical (tangible and intangible). The example of
intangible object is banking system.
• An object has three characteristics:
state: represents data (value) of an object.
behaviour: represents the behaviour (functionality) of an object such as deposit,
withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

3
Simple Example of Object and Class
• In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.

class Student{
int id; //data member (also instance variable)
String name; //data member(also instance variable)

public static void main(String args[]){


Student s1=new Student(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
O/P: 0
null

4
Example of Object and class that
maintains the records of students
class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name);}//method
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
O/P: 111 Karan
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan"); 222 Aryan
s1.displayInformation();
s2.displayInformation(); 5
As you see in the above figure, object gets the memory in Heap area and reference variable refers to the object
allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.

6
Anonymous object
• Anonymous simply means nameless. An object that have no reference is known as
anonymous object.
• If you have to use an object only once, anonymous object is a good approach.
class Calculation{

void fact(int n){


int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5); //calling method with annonymous object
}
}
7
Access Modifiers in java
• The access modifiers in java specifies accessibility (scope) of a data
member, method, constructor or class.
• There are 4 types of java access modifiers:
private
default
protected
public

8
private access modifier
• The private access modifier is accessible only within class.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

9
default access modifier
• If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}

10
protected access modifier
• The protected access modifier is accessible within package and outside the package but through
inheritance only.
• The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
} 11
public access modifier
• The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} 12
}
Understanding all java access modifiers

Access Modifier within class within package outside package outside package
by subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

13
Final Keyword In Java

• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
variable
method
Class

14
Java final variable
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}

O/P: Compile time error


15
Java final method
• If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
O/P: Compile Time Error

16
Is final method inherited?
• Yes, final method is inherited but you cannot override it.

class Bike{
final void run(){System.out.println("running...");}
}
class Honda extends Bike{
public static void main(String args[]){
new Honda().run();
}
}
O/P: running…
17
Java final class
• If you make any class as final, you cannot extend it.

final class Bike{}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
O/P: Compile Time Error

18
Can we declare a constructor final?
• No, because constructor is never inherited.

19
Can we initialize blank final variable?
• Yes, but only in constructor.

class Bike{
final int speedlimit; //blank final variable

Bike()
{
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike();
}
}

20
static blank final variable
• A static final variable that is not initialized at the time of declaration is
known as static blank final variable. It can be initialized only in static block.

class A{
static final int data; //static final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}

Note: We can not even initialized the static final variables in constructor.

21
Polymorphism in Java
• Polymorphism in java is a concept by which we can perform a single
action by different ways. Polymorphism is derived from 2 greek
words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
• There are two types of polymorphism in java:
compile time polymorphism
runtime polymorphism.

• We can perform polymorphism in java by method overloading and


method overriding.
22
Difference between method overloading
and method overriding in java
No.
Method Overloading Method Overriding
1) Method overloading is used to increase the readability of the Method overriding is used to provide the specific implementation of
program. the method that is already provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same.

4) Method overloading is the example of compile time Method overriding is the example of run time polymorphism.
polymorphism.

5) In java, method overloading can't be performed by changing Return type must be same in method overriding.
return type of the method only. Return type can be same or
different in method overloading. But you must have to change the
parameter.
23
Java Method Overloading example
class ABC{
public int add(int a, int b){
return(a+b);
Note: There are two ways to overload the method in java
} 1. By changing number of arguments
public int add(int a, int b, int c){ 2. By changing the data type
return (a+b+c);
In java, Method Overloading is not possible by
} changing the return type of the method.
public static void main(String args[]){
ABC a1=new ABC();
System.out.println(a1.add(10, 20));
System.out.println(a1.add(10, 20, 30));
}
} 24
Java Method Overriding example
class Animal{
void eat()
{
System.out.println("eating...");
} }
class Dog extends Animal{
void eat()
{
System.out.println("eating bread...");
} }
Class Test
{
public static void main(String args[])
{
Animal a1=new Animal();
a1.eat();
Animal a2=new Dog();
a2.eat();
} 25
Can we overload main() method?
• Yes, you can have any number of main methods in a class by method overloading. Let's
see the simple example:
class Overloading1{
public static void main(int a){
System.out.println(a);
}

public static void main(String args[]){


System.out.println("main() method invoked");
main(10);
} O/P: main() method invoked
} 10

26
Can we override main() method?
• No you cant.
• Static methods cant be overridden. That’s because call to overridden
methods are resolved at runtime depending upon the calling object.
And since static methods are called by their class names (i.e
classname.method()) they cant be overridden.

27
Wrapper Class
• Wrapper class in java provides the mechanism to convert primitive
into object and object into primitive.
• The eight classes of java.lang package are known as wrapper classes
in java. The list of eight wrapper classes are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Example
public class WrapperExample
{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}
Inner Class
• Inner class or nested class is a class i.e. declared inside the class or
interface.
• Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}

30
Inner class example
class TestMemberOuter
{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestMemberOuter obj=new TestMemberOuter();
TestMemberOuter.Inner in=obj.new Inner();
in.msg();
}
}
O/P: data is 30
31
Java Anonymous Inner Class
• A class that have no name is known as anonymous inner class in java. It
should be used if you have to override method of class or interface.

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
32
Example
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){
System.out.println("nice fruits");
}
};
p.eat();
}
} O/P: nice fruits

You might also like