Вы находитесь на странице: 1из 89

Object Oriented Programming concepts

Introduction
This tutorial will help you to understand about Java OOPS concepts with examples. Lets
discuss about what are the features of Object Oriented Programming. Writing object-oriented
programs involves creating classes, creating objects from those classes, and creating
applications, which are stand-alone executable programs that use those objects.
A class is a template, blueprint,or contract that defines what an objects data fields and methods
will be. An object is an instance of a class. You can create many instances of a class. A Java
class uses variables to define data fields and methods to define actions. Additionally,a class
provides methods of a special type, known as constructors, which are invoked to create a new
object. A constructor can perform any action, but constructors are designed to perform
initializing actions, such as initializing the data fields of objects.

Objects are made up of attributes and methods. Attributes are the characteristics that define an
object; the values contained in attributes differentiate objects of the same class from one another.
To understand this better lets take example of Mobile as object. Mobile has characteristics like
model, manufacturer, cost, operating system etc. So if we create Samsung mobile object and

IPhone mobile object we can distinguish them from characteristics. The values of the attributes
of an object are also referred to as the objects state.
There are three main features of OOPS.
1) Encapsulation
2) Inheritance
3) Polymorphism
Lets we discuss about the about features in details.

Encapsulation
Encapsulation means putting together all the variables (instance variables) and the methods into
a single unit called Class. It also means hiding data and methods within an Object. Encapsulation
provides the security that keeps data and methods safe from inadvertent changes. Programmers
sometimes refer to encapsulation as using a black box, or a device that you can use without
regard to the internal mechanisms. A programmer can access and use the methods and data
contained in the black box but cannot change them. Below example shows Mobile class with
properties, which can be set once while creating object using constructor arguments. Properties
can be accessed using getXXX() methods which are having public access modifiers.
view plainprint?
1. package oopsconcept;
2. public class Mobile {
3.
private String manufacturer;
4.
private String operating_system;
5.
public String model;
6.
private int cost;
7.
//Constructor to set properties/characteristics of object
8.
Mobile(String man, String o,String m, int c){
9.
this.manufacturer = man;
10.
this.operating_system=o;
11.
this.model=m;
12.
this.cost=c;
13. }
14. //Method to get access Model property of Object
15. public String getModel(){
16.
return this.model;
17. }
18. // We can add other method to get access to other properties
19. }

Inheritance
An important feature of object-oriented programs is inheritancethe ability to create classes that
share the attributes and methods of existing classes, but with more specific features. Inheritance
is mainly used for code reusability. So you are making use of already written class and further
extending on that. That why we discussed about the code reusability the concept. In general one
line definition we can tell that deriving a new class from existing class, its called as Inheritance.
You can look into the following example for inheritance concept. Here we have Mobile class
extended by other specific class like Android and Blackberry.
view plainprint?
1. package oopsconcept;
2. public class Android extends Mobile{
3.
//Constructor to set properties/characteristics of object
4.
Android(String man, String o,String m, int c){
5.
super(man, o, m, c);
6.
}
7.
//Method to get access Model property of Object
8.
public String getModel(){
9.
return "This is Android Mobile- " + model;
10.
}
11. }
view plainprint?
1. package oopsconcept;
2. public class Blackberry extends Mobile{
3.
//Constructor to set properties/characteristics of object
4.
Blackberry(String man, String o,String m, int c){
5.
super(man, o, m, c);
6.
}
7.
public String getModel(){
8.
return "This is Blackberry-"+ model;
9.
}
10. }

Polymorphism
In Core Java Polymorphism is one of easy concept to understand. Polymorphism definition is
that Poly means many and morphos means forms. It describes the feature of languages that
allows the same word or symbol to be interpreted correctly in different situations based on the
context. There are two types of Polymorphism available in Java. For example, in English the
verb run means different things if you use it with a footrace, a business, or a computer.
You understand the meaning of run based on the other words used with it. Object-oriented

programs are written so that the methods having same name works differently in different
context. Java provides two ways to implement polymorphism.

Static Polymorphism (compile time polymorphism/ Method


overloading):
The ability to execute different method implementations by altering the argument used with the
method name is known as method overloading. In below program we have three print methods
each with different arguments. When you properly overload a method, you can call it providing
different argument lists, and the appropriate version of the method executes.
view plainprint?
1. package oopsconcept;
2. class Overloadsample {
3.
public void print(String s){
4.
System.out.println("First Method with only String- "+ s);
5.
}
6.
public void print (int i){
7.
System.out.println("Second Method with only int- "+ i);
8.
}
9.
public void print (String s, int i){
10.
11.
System.out.println("Third Method with both- "+ s + "--" + i);
12. }
13. }
14. public class PolymDemo {
15. public static void main(String[] args) {
16.
Overloadsample obj = new Overloadsample();
17.
obj.print(10);
18.
obj.print("Amit");
19.
obj.print("Hello", 100);
20. }
21. }

Output :

Dynamic Polymorphism (run time polymorphism/ Method


Overriding)
When you create a subclass by extending an existing class, the new subclass contains data and
methods that were defined in the original superclass. In other words, any child class object has
all the attributes of its parent. Sometimes, however, the superclass data fields and methods are
not entirely appropriate for the subclass objects; in these cases, you want to override the parent
class members. Lets take example used in inheritance explanation.
view plainprint?
1. package oopsconcept;
2. public class OverridingDemo {
3.
public static void main(String[] args) {
4.
//Creating Object of SuperClass and calling getModel Method
5.
Mobile m = new Mobile("Nokia", "Win8", "Lumia",10000);
6.
System.out.println(m.getModel());
7.
//Creating Object of Sublcass and calling getModel Method
8.
Android a = new Android("Samsung", "Android", "Grand",30000);
9.
System.out.println(a.getModel());
10.
//Creating Object of Sublcass and calling getModel Method
11.
Blackberry b = new Blackberry("BlackB", "RIM", "Curve",20000);
12.
System.out.println(b.getModel());
13. }
14. }

Abstraction
All programming languages provide abstractions. It can be argued that the complexity of the
problems youre able to solve is directly related to the kind and quality of abstraction. An
essential element of object-oriented programming is abstraction. Humans manage complexity
through abstraction. When you drive your car you do not have to be concerned with the exact
internal working of your car(unless you are a mechanic). What you are concerned with is
interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc.
Various manufacturers of car has different implementation of car working but its basic interface
has not changed (i.e. you still use steering wheel, brake pedal, accelerator pedal etc to interact
with your car). Hence the knowledge you have of your car is abstract.
A powerful way to manage abstraction is through the use of hierarchical classifications. This
allows you to layer the semantics of complex systems, breaking them into more manageable
pieces. From the outside, the car is a single object. Once inside, you see that the car consists of
several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so on.
In turn, each of these subsystems is made up of more specialized units. For instance, the sound
system consists of a radio, a CD player, and/or a tape player. The point is that you manage the
complexity of the car (or any other complex system)through the use of hierarchical abstractions.

An abstract class is something which is incomplete and you can not create instance of abstract
class. If you want to use it you need to make it complete or concrete by extending it. A class is
called concrete if it does not contain any abstract method and implements all abstract method
inherited from abstract class or interface it has implemented or extended. By the way Java has
concept of abstract classes, abstract method but a variable can not be abstract in Java.
Lets take an example of Java Abstract Class called Vehicle. When I am creating a class called
Vehicle, I know there should be methods like start() and Stop() but don't know start and stop
mechanism of every vehicle since they could have different start and stop mechanism e.g some
can be started by kick or some can be by pressing buttons.
Advantage of Abstraction is if there is new type of vehicle introduced we might just need to add
one class which extends Vehicle Abstract class and implement specific methods. Interface of
start and stop method would be same.
view plainprint?
1. package oopsconcept;
2.
3. public abstract class VehicleAbstract {
4.
5.
public abstract void start();
6.
7.
public void stop(){
8.
System.out.println("Stopping Vehicle in abstract class");
9.
}
10. }
11.
12. class TwoWheeler extends VehicleAbstract{
13.
14. @Override
15. public void start() {
16.
System.out.println("Starting Two Wheeler");
17. }
18. }
19. class FourWheeler extends VehicleAbstract{
20.
21. @Override
22. public void start() {
23.
System.out.println("Starting Four Wheeler");
24.
25. }
26.
27. }
view plainprint?

1. package oopsconcept;
2.
3. public class VehicleTesting {
4.
5.
public static void main(String[] args) {
6.
VehicleAbstract my2Wheeler = new TwoWheeler();
7.
VehicleAbstract my4Wheeler = new FourWheeler();
8.
9.
my2Wheeler.start();
10.
my2Wheeler.stop();
11.
12.
my4Wheeler.start();
13.
my4Wheeler.stop();
14. }
15. }

Output :

Summary
- See more at: http://www.w3resource.com/java-tutorial/java-object-orientedprogramming.php#sthash.Ainy6EZX.dpuf

What is Class in Java Programming with


General Example
When I first about Class in Java I just thought what is this Class in Java and from that date to now
Whenever we talk about java its really incomplete without classes, every one who are little bit familiar
with java knows its purely object oriented language means every thing we discuss in java as object
.so its very important for learner or anyone who is keen to know about java should know about java
class then only they can move forward on java world.

In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class
including members, field and method.If you have just started programming in Java or learning Please
check my article How to Set Path for Java and How to set ClassPath for Java covering two important
concept PATH and CLASSPATH.

Class in Java Programming Example


What is Java Class?

Java class is nothing but a template for object you are going to create or its
a blue print by using this we create an object. In simple word we can say its a specification or a
pattern which we define and every object we define will follow that pattern.

What does Java Class Consist

When we create class in java the first step is keyword class and then name of the class or identifier
we can say.

Next is class body which starts with curly braces {} and between this all things related with that class
means their property and method will come here.

Template is:

Class (name of the class) {

(Here define member of class)

Access level of class:

Java class has mainly two type of access level:

Default: class objects are accessible only inside the package.

Public: class objects are accessible in code in any package.

What are members of Class?


When we create a class its totally incomplete without defining any member of this class same like we
can understand one family is incomplete if they have no members.

Field: field is nothing but the property of the class or object which we are going to create .for example
if we are creating a class called computer then they have property like model, mem_size, hd_size,
os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of
object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of
the class.
Each field and method has an access level:

private: accessible only in this class


package or default: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Real world example of Class in Java Programming:

In real world if we want to understand about the class everything of same quality can be visualize as
a class e.g. men,women,birds ,bicycles ,cars or we can say vehicle .
The entire vehicle will make one class they have the property like no_of_wheels, color, model, brand
etc.now we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method on that
class. Similarly all human being also can be one class now their member will be a men ,women
,child.,isAlive() ,isDeath() can be their method or behavior of that class .again we can make Men or
women a separate class and define their property and method accordingly,
In short in java every problem we get solution can be think in terms of class and object.

One Java class example:

Class Stock {
Public commodity;
Public price;
Public void buy (int no_of commodity) {}
Public boolean sale () {}
}

In this example Stock is called Class and commodity, price are field and buy() and sale() are two
methods defined inside class. To access elements of Class you need to create an instance of class
Stock. You can create instance of Class using keyword new as shown below

Stock highBetaStock = new Stock();

For calling method of Stock just call by using instance.

highBetaStock.buy(1000);
highBetaStock.sell();

Read more: http://javarevisited.blogspot.com/2011/10/class-in-java-programminggeneral.html#ixzz3AvGmFjiU

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java
supports the following fundamental concepts:

Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing

In this chapter, we will look into the concepts Classes and Objects.

Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blue print that describes the behaviors/states
that object of its type support.

Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many
objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging, running
If you compare the software object with a real world object, they have very similar
characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-toobject communication is done via methods.

Classes in Java:

A class is a blue print from which individual objects are created.


A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}

A class can contain any of the following variable types.

Local variables: Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance variables can
be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any
method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Below mentioned are some of the important topics that need to be discussed when looking into
classes of the Java Language.

Constructors:
When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Example of a constructor is given below:

public class Puppy{


public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
}
}

Java also supports Singleton Classes where you would be able to create only one instance of a
class.

Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:

Declaration: A variable declaration with a variable name with an object type.


Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Example of creating an object is given below:


public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy

Accessing Instance Variables and Methods:


Instance variables and methods are accessed via created objects. To access an instance variable
the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example:
This example explains how to access instance variables and methods of a class:
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}

If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
Puppy's age is :2
Variable Value :2

Source file declaration rules:


As the last part of this section let's now look into the source file declaration rules. These rules are
essential when declaring classes, import statements and package statements in a source file.

There can be only one public class per source file.


A source file can have multiple non public classes.
The public class name should be the name of the source file as well which should be
appended by .java at the end. For example : The class name is . public class Employee{}
Then the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should be the first
statement in the source file.
If import statements are present then they must be written between the package statement
and the class declaration. If there are no package statements then the import statement
should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It is
not possible to declare different import and/or package statements to different classes in
the source file.

Classes have several access levels and there are different types of classes; abstract classes, final
classes, etc. I will be explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called Inner
classes and Anonymous classes.

Java Package:
In simple, it is a way of categorizing the classes and interfaces. When developing applications in
Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a
must as well as makes life much easier.

Import statements:
In Java if a fully qualified name, which includes the package and the class name, is given then
the compiler can easily locate the source code or classes. Import statement is a way of giving the
proper location for the compiler to find that particular class.
For example, the following line would ask compiler to load all the classes available in directory
java_installation/java/io :
import java.io.*;

A Simple Case Study:


For our case study, we will be creating two classes. They are Employee and EmployeeTest.
First open notepad and add the following code. Remember this is the Employee class and the
class is a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables name, age, designation and salary. The class has
one explicitly defined constructor, which takes a parameter.
import java.io.*;
public class Employee{
String name;
int age;
String designation;
double salary;
// This is the constructor of the class Employee
public Employee(String name){
this.name = name;
}
// Assign the age of the Employee to the variable age.
public void empAge(int empAge){
age = empAge;
}
/* Assign the designation to the variable designation.*/
public void empDesignation(String empDesig){
designation = empDesig;
}
/* Assign the salary to the variable
salary.*/
public void empSalary(double empSalary){
salary = empSalary;
}
/* Print the Employee details */
public void printEmployee(){
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}

As mentioned previously in this tutorial, processing starts from the main method. Therefore inorder for us to run this Employee class there should be main method and objects should be
created. We will be creating a separate class for these tasks.
Given below is the EmployeeTest class, which creates two instances of the class Employee and
invokes the methods for each object to assign values for each variable.
Save the following code in EmployeeTest.java file
import java.io.*;
public class EmployeeTest{
public static void main(String args[]){
/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");
// Invoking methods for each object created
empOne.empAge(26);

empOne.empDesignation("Senior Software Engineer");


empOne.empSalary(1000);
empOne.printEmployee();
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}

Now, compile both the classes and then run EmployeeTest to see the result as follows:
C :> javac Employee.java
C :> vi EmployeeTest.java
C :> javac EmployeeTest.java
C :> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0

Java - Inheritance
Advertisements
Previous Page
Next Page

Inheritance can be defined as the process where one object acquires the properties of another.
With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance, the most commonly used keyword would be extends and
implements. These words would determine whether one object IS-A type of another. By using
these keywords we can make one object acquire the properties of another object.

IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
public class Animal{
}

public class Mammal extends Animal{


}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}

Now, based on the above example, In Object Oriented terms, the following are true:

Animal is the superclass of Mammal class.


Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say:

Mammal IS-A Animal


Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result:


true
true
true

Since we have a good understanding of the extends keyword let us look into how the
implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.

Example:
public interface Animal {}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}

The instanceof Keyword:


Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal{
public static void main(String args[]){
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result:


true
true
true

HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HASA certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:

public class Vehicle{}


public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class., which makes it possible to
reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{}

However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.

Java - Overriding
Advertisements
Previous Page
Next Page

In the previous chapter, we talked about super classes and sub classes. If a class inherits a
method from its super class, then there is a chance to override the method provided that it is not
marked final.
The benefit of overriding is: ability to define a behavior that's specific to the subclass type which
means a subclass can implement a parent class method based on its requirement.
In object-oriented terms, overriding means to override the functionality of an existing method.

Example:
Let us look at an example.

class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}

This would produce the following result:


Animals can move
Dogs can walk and run

In the above example, you can see that the even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the
reference type. However, in the runtime, JVM figures out the object type and would run the
method that belongs to that particular object.
Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.
Consider the following example :
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){

System.out.println("Dogs can bark");


}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}

This would produce the following result:


TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^

This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.

Rules for method overriding:

The argument list should be exactly the same as that of the overridden method.
The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level. For
example: if the superclass method is declared public then the overridding method in the
sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared public
or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
Constructors cannot be overridden.

Using the super keyword:


When invoking a superclass version of an overridden method the super keyword is used.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}

This would produce the following result:


Animals can move
Dogs can walk and run

Java - Polymorphism
Advertisements
Previous Page
Next Page

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.

Example:
Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:

A Deer IS-A Animal


A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations
are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d,a,v,o refer to the same Deer object in the heap.

Virtual Methods:
In this section, I will show you how the behavior of overridden methods in Java allows you to
take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its
parent. An overridden method is essentially hidden in the parent class, and is not invoked unless
the child class uses the super keyword within the overriding method.
/* File name : Employee.java */
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Now suppose we extend Employee class as follows:


/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
setSalary(salary);

}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Now, you study the following program carefully and try to determine its output:
/* File name : VirtualDemo.java */
public class VirtualDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

This would produce the following result:


Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference -Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference-Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects . one using a Salary reference s, and the other using an
Employee reference e.

While invoking s.mailCheck() the compiler sees mailCheck() in the Salary class at compile time,
and the JVM invokes mailCheck() in the Salary class at run time.
Invoking mailCheck() on e is quite different because e is an Employee reference. When the
compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At
run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and the methods are referred to as
virtual methods. All methods in Java behave in this manner, whereby an overridden method is
invoked at run time, no matter what data type the reference is that was used in the source code at
compile time.

Java - Abstraction
Advertisements
Previous Page
Next Page

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot create an instance of the
abstract class.
If a class is abstract and cannot be instantiated, the class does not have much use unless it is
subclass. This is typically how abstract classes come about during the design phase. A parent
class contains the common functionality of a collection of child classes, but the parent class itself
is too abstract to be used on its own.

Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.
/* File name : Employee.java */
public abstract class Employee
{
private String name;

private String address;


private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Notice that nothing is different in this Employee class. The class is now abstract, but it still has
three fields, seven methods, and one constructor.
Now if you would try as follows:
/* File name : AbstractDemo.java */
public class AbstractDemo
{
public static void main(String [] args)
{
/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
System.out.println("\n Call mailCheck using Employee reference--");

e.mailCheck();
}
}

When you would compile above class then you would get the following error:
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error

Extending Abstract Class:


We can extend Employee class in normal way as follows:
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary
object will inherit the three fields and seven methods from Employee.
/* File name : AbstractDemo.java */

public class AbstractDemo


{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

This would produce the following result:


Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference -Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference-Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as
abstract.
The abstract keyword is also used to declare a method as abstract. An abstract method consists of
a method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not
curly braces as follows:
public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract double computePay();
//Remainder of class definition
}

Declaring a method as abstract has two results:

The class must also be declared abstract. If a class contains an abstract method, the class
must be abstract as well.
Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they must be
abstract and any of their children must override it.
Eventually, a descendant class has to implement the abstract method; otherwise, you would have
a hierarchy of abstract classes that cannot be instantiated.
If Salary is extending Employee class, then it is required to implement computePay() method as
follows:
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; // Annual salary
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
//Remainder of class definition
}

Java - Encapsulation
Advertisements
Previous Page
Next Page

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private and providing access to the
fields via public methods. If a field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred
to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without
breaking the code of others who use our code. With this feature Encapsulation gives
maintainability, flexibility and extensibility to our code.

Example:
Let us look at an example that depicts encapsulation:
/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}

The public methods are the access points to this class' fields from the outside java world.
Normally, these methods are referred as getters and setters. Therefore any class that wants to
access the variables should access them through these getters and setters.
The variables of the EncapTest class can be access as below::
/* File name : RunEncap.java */
public class RunEncap{

public static void main(String args[]){


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+
" Age : "+ encap.getAge());
}
}

This would produce the following result:


Name : James Age : 20

Benefits of Encapsulation:

The fields of a class can be made read-only or write-only.


A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A class can change the data
type of a field and users of the class do not need to change any of their code.

Java - Interfaces
Advertisements
Previous Page
Next Page

An interface is a collection of abstract methods. A class implements an interface, thereby


inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The bytecode of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

You cannot instantiate an interface.


An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:

Example:
Let us look at an example that depicts encapsulation:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {

public void eat();


public void travel();
}

Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce the following result:


Mammal eats
Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

A class can implement more than one interface at a time.


A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend
another class.

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain
any methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:
package java.util;
public interface EventListener
{}

An interface with no methods in it is referred to as a tagging interface. There are two basic
design purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of
other interfaces in the Java API, you can use a tagging interface to create a common parent
among a group of interfaces. For example, when an interface extends EventListener, the JVM
knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not
have any), but the class becomes an interface type through polymorphism.

Java - Packages
Advertisements
Previous Page
Next Page

Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and
annotations ) providing access protection and name space management.

Some of the existing packages in Java are::

java.lang - bundles the fundamental classes


java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.

Creating a package:
When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.

Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}

Now, put an implementation in the same package animals:


package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){

System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Now, you compile these two files and put them in a sub-directory called animals and try to run
as follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels

The import Keyword:


If a class wants to use another class in the same package, the package name does not need to be
used. Classes in the same package find each other without any special syntax.

Example:
Here, a class named Boss is added to the payroll package that already contains Employee. The
Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by
the following Boss class.
package payroll;
public class Boss
{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}

What happens if Boss is not in the payroll package? The Boss class must then use one of the
following techniques for referring to a class in a different package.

The fully qualified name of the class can be used. For example:

payroll.Employee

The package can be imported using the import keyword and the wild card (*). For
example:

import payroll.*;

The class itself can be imported using the import keyword. For example:

import payroll.Employee;

Note: A class file can contain any number of import statements. The import statements must
appear after the package statement and before the class declaration.

The Directory Structure of Packages:


Two major results occur when a class is placed in a package:

The name of the package becomes a part of the name of the class, as we just discussed in
the previous section.
The name of the package must match the directory structure where the corresponding
bytecode resides.

Here is simple way of managing your files in Java:


Put the source code for a class, interface, enumeration, or annotation type in a text file whose
name is the simple name of the type and whose extension is .java. For example:
// File Name :

Car.java

package vehicle;
public class Car {
// Class implementation.
}

Now, put the source file in a directory whose name reflects the name of the package to which the
class belongs:
....\vehicle\Car.java

Now, the qualified class name and pathname would be as below:

Class name -> vehicle.Car


Path name -> vehicle\Car.java (in windows)

In general, a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with
com.apple. Each component of the package name corresponds to a subdirectory.
Example: The company had a com.apple.computers package that contained a Dell.java source
file, it would be contained in a series of subdirectories like this:
....\com\apple\computers\Dell.java

At the time of compilation, the compiler creates a different output file for each class, interface
and enumeration defined in it. The base name of the output file is the name of the type, and its
extension is .class
For example:
// File Name: Dell.java
package com.apple.computers;
public class Dell{
}
class Ups{
}

Now, compile this file as follows using -d option:


$javac -d . Dell.java

This would put compiled files as follows:


.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class

You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com.apple.computers.*;

Like the .java source files, the compiled .class files should be in a series of directories that reflect
the package name. However, the path to the .class files does not have to be the same as the path
to the .java source files. You can arrange your source and class directories separately, as:
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class

By doing this, it is possible to give the classes directory to other programmers without revealing
your sources. You also need to manage source and class files in this manner so that the compiler
and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with
the CLASSPATH system variable. Both the compiler and the JVM construct the path to your
.class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current directory
and the JAR file containing the Java platform classes so that these directories are automatically
in the class path.

Set CLASSPATH System Variable:


To display the current CLASSPATH variable, use the following commands in Windows and
UNIX (Bourne shell):

In Windows -> C:\> set CLASSPATH


In UNIX -> % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use :

In Windows -> C:\> set CLASSPATH=


In UNIX -> % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable:

In Windows -> set CLASSPATH=C:\users\jack\java\classes


In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class. Before learning
abstract class, let's understand the abstraction first.
Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction

There are two ways to achieve abstraction in java


1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Syntax to declare the abstract class
1. abstract class <class_name>{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
Syntax to define the abstract method
1. abstract return_type <method_name>();//no braces{}
Example of abstract class that have abstract method

In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
1.
2.
3.
4.
5.
6.
7.
8.
9.

abstract class Bike{


abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();

10. obj.run();
11. }
12. }
Output:running safely..

Understanding the real scenario of abstract class

In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw method of Rectangle class
will be invoked.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

abstract class Shape{


abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
class Test{
public static void main(String args[]){
Shape s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
}
}

Output:drawing circle

Abstract class having constructor, data member, methods etc.


Note: An abstract class can have data member, abstract method, method body, constructor and
even main() method.
1. //example of abstract class that have method body

2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

abstract class Bike{


abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Output:running safely..
gear changed

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

//example of abstract class having constructor, field and method


abstract class Bike
{
int limit=30;
Bike(){System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");}
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.getDetails();
System.out.println(obj.limit);
}
}

Output:constructor is invoked
running safely..
it has two wheels
30

Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike{
2. abstract void run();
3. }

Output:compile time error

Rule: If you are extending any abstact class that have abstract method, you must either provide
the implementation of the method or make this class abstract.
Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.

interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

Output:I
I
I
I

am
am
am
am

a
b
c
d

Interface in Java
1. Interface

2.
3.
4.
5.
6.

Example of Interface
Multiple inheritance by Interface
Why multiple inheritance is supported in Interface while it is not supported in case of class.
Marker Interface
Nested Interface

An interface is a blueprint of a class. It has static constants and abstract methods.


The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Interface?


There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.


By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Simple example of Interface


In this example, Printable interface have only one method, its implementation is provided in the A class.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

interface printable{
void print();
}
class A implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}

Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}

Output:Hello
Welcome

Q) Multiple inheritance is not supported in case of class but


it is supported in case of interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class.
But it is supported in case of interface because there is no ambiguity as implementation is provided by

the implementation class. For example:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

interface Printable{
void print();
}
interface Showable{
void print();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}

Output:Hello

As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class A, so there is no ambiguity.

Note: A class implements interface but One interface extends another interface .
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class A implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}

19. }
Output:Hello
Welcome

Que) What is marker or tagged interface ?


An interface that have no member is known as marker or tagged interface. For example: Serializable,
Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM
may perform some useful operation.

1. //How Serializable interface is written?


2.
3. public interface Serializable{
4. }

Nested Interface

Note: An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4.
void msg();
5. }
6. }

Access Modifiers
1.
2.
3.
4.
5.
6.

private access modifier


Role of private constructor
default access modifier
protected access modifier
public access modifier
Applying access modifier with method overriding

There are two types of modifiers in java: access modifier and non-access modifier. The access
modifiers specifies accessibility (scope) of a datamember, method, constructor or class.
There are 4 types of access modifiers:
1.
2.
3.
4.

private
default
protected
public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc. Here, we will learn access modifiers.

1) private
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile
time error.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

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
}
}

Role of Private Constructor:


If you make any class constructor private, you cannot create the instance of that class from outside the
class. For example:

1. class A{
2. private A(){}//private constructor
3.
4. void msg(){System.out.println("Hello java");}

5.
6.
7.
8.
9.
10.
11.

}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.


2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only
within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.

1.
2.
3.
4.
5.
6.

//save by A.java

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

//save by B.java

package pack;
class A{
void msg(){System.out.println("Hello");}
}

package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.

3) protected

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.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

1.
2.
3.
4.
5.
6.

//save by A.java

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

//save by B.java

package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

Output:Hello

4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
1.
2.
3.
4.
5.

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

6. }
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.


Access Modifier within class within package outside package by subclass only outside package
Private

Default

Protected

Public

Applying access modifier with method overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}

11. }

Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule i.e
mixed of several medicines.

We can create a fully encapsulated class by making all the


data members of the class private. Now we can use setter and getter methods to set and get the
data in it.
Java Bean is the example of fully encapsulated class.
Advantage of Encapsulation

By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater
than 100 only, you can write the logic inside the setter method.
Simple example of encapsulation in java

Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.
1.
2.
3.
4.
5.
6.
7.
8.
9.

//save as Student.java
package com.javatpoint;
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){

10. this.name=name
11. }
12. }
1.
2.
3.
4.
5.
6.
7.
8.
9.

//save as Test.java
package com.javatpoint;
class Test{
public static void main(String[] args){
Student s=new Student();
s.setname("vijay");
System.out.println(s.getName());
}
}

Compile By: javac -d . Test.java


Run By: java com.javatpoint.Test
Output: vijay

Object class in Java


The Object class is the parent class of all the classes in java bydefault. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't what object would be returned from this method

The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:
Method

Description

public final ClassgetClass()

returns the Class class object of this object. The Class class
can further be used to get the metadata of this class.

public int hashCode()

returns the hashcode number for this object.

public boolean equals(Object obj)

compares the given object to this object.

protected Object clone() throws


CloneNotSupportedException

creates and returns the exact copy (clone) of this object.

public String toString()

returns the string representation of this object.

public final void notify()

wakes up single thread, waiting on this object's monitor.

public final void notifyAll()

wakes up all the threads, waiting on this object's monitor.

public final void wait(long timeout)throws


InterruptedException

causes the current thread to wait for the specified


milliseconds, until another thread notifies (invokes notify()
or notifyAll() method).

public final void wait(long timeout,int

causes the current thread to wait for the specified


miliseconds and nanoseconds, until another thread

nanos)throws InterruptedException

notifies (invokes notify() or notifyAll() method).

public final void wait()throws


InterruptedException

causes the current thread to wait, until another thread


notifies (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable

is invoked by the garbage collector before object is being


garbage collected.

We will have the detailed learning of these methods in next chapters.

Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization

Constructor is a special type of method that is used to initialize the object.


Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Rules for creating constructor

There are basically two rules defined for the constructor.


1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of constructors

There are two types of constructors:


1. default constructor (no-arg constructor)
2. parameterized constructor

1) Default Constructor
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.

1. class Bike{

2.
3.
4.
5.
6.
7.
8.

Bike(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike b=new Bike();
}
}

Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Que)What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Example of default constructor that displays the default values
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

class Student{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}

Output:0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.

Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

1. class Student{
2.
int id;
3.
String name;
4.
5.
Student(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Output:111 Karan
222 Aryan

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type.
Example of Constructor Overloading
1. class Student{
2.
int id;

3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22. }

String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}

Output:111 Karan 0
222 Aryan 25

What is the difference between constructor and method ?


There are many differences between constructors and methods. They are given below.
Constructor

Method

Constructor is used to initialize the state of an object.

Method is used to expose behaviour of


an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you don't


have any constructor.

Method is not provided by compiler in


any case.

Constructor name must be same as the class name.

Method name may or may not be same


as class name.

Copying the values of one object to another like copy constructor in C++

There are many ways to copy the values of one object into another. They are:

By constructor
By assigning the values of one object into another
By clone() method of Object class

In this example, we are going to copy the values of one object into another using constructor.

1. class Student{
2.
int id;
3.
String name;
4.
Student(int i,String n){
5.
id = i;
6.
name = n;
7.
}
8.
9.
Student(Student s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
17. Student s2 = new Student(s1);
18. s1.display();
19. s2.display();
20. }
21. }
Output:111 Karan
111 Karan

Copying the values of one object to another without constructor


We can copy the values of one object into another by assigning the objects values to another object. In
this case, there is no need to create the constructor.

1. class Student{
2.
int id;
3.
String name;
4.
Student(int i,String n){
5.
id = i;

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19. }

name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}

Output:111 Karan
111 Karan

Que)Does constructor return any value?


Ans:yes,that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any operation in
the constructor as you perform in the method.

static keyword
1.
2.
3.
4.
5.
6.
7.
8.

Static variable
Program of counter without static variable
Program of counter with static variable
Static method
Restrictions for static method
Why main method is static ?
Static block
Can we execute a program without main method ?

The static keyword is used in java mainly for memory management. We may apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
The static can be:
1.
2.
3.
4.

variable (also known as class variable)


method (also known as class method)
block
nested class

1) static variable
If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
1. class Student{
2.
int rollno;
3.
String name;
4.
String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is created.All student have its unique rollno and name so instance data
member is good.Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.
static property is shared to all objects.
Example of static variable
1. //Program of static variable
2.
3. class Student{
4.
int rollno;
5.
String name;

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

static String college ="ITS";


Student(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.display();
}
}

Output:111 Karan ITS


222 Aryan ITS

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}}

Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();

15. }}
Output:1
2
3

2) static method

If you apply static keyword with any method, it is known as static method

A static method belongs to the class rather than object of a class.


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

Example of static method


1. //Program of changing the common property of all objects(static field).
2.
3. class Student{
4.
int rollno;
5.
String name;
6.
static String college = "ITS";
7.
8.
static void change(){
9.
college = "BBDIT";
10. }
11.
12. Student(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
17. void display (){System.out.println(rollno+" "+name+" "+college);}
18.
19. public static void main(String args[]){
20. Student.change();
21.
22. Student s1 = new Student (111,"Karan");
23. Student s2 = new Student (222,"Aryan");
24. Student s3 = new Student (333,"Sonoo");
25.
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal calculation


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

//Program to get cube of a given number by 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);
}
}

Output:125

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

1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:Compile Time Error

Que)why main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm create object
first then call main() method that will lead the problem of extra memory allocation.

3)static block

Is used to initialize the static data member.


It is executed before main method at the time of classloading.

Example of static block


1. class A{
2.
3. static{System.out.println("static block is invoked");}
4.
5. public static void main(String args[]){
6.
System.out.println("Hello main");
7. }
8. }
Output:static block is invoked
Hello main

Que)Can we execute a program without main() method?


Ans)Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

1. class A{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Output:static block is invoked (if not JDK7)

this keyword
1. this keyword
2. Usage of this keyword
1. to refer the current class instance variable
2. to invoke the current class constructor
3. to invoke the current class method
4. to pass as an argument in the method call
5. to pass as an argument in the constructor call
6. to return the current class instance

3. Proving this keyword

There can be a lot of usage of this keyword. In java, this is a reference variable that refers to
the current object.

Usage of this keyword


Here is given the 6 usage of this keyword.
1.
2.
3.
4.
5.

this keyword can be used to refer current class instance variable.


this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.
Suggestion:If you are beginner to java, lookup only two usage of this keyword.

1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:

1. class student{
2.
int id;
3.
String name;
4.
5.
student(int id,String name){
6.
id = id;

7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17. }

name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
student s1 = new student(111,"Karan");
student s2 = new student(321,"Aryan");
s1.display();
s2.display();
}

Output:0 null
0 null

In the above example, parameter (formal arguments) and instance variables are same that is why we are
using this keyword to distinguish between local variable and instance variable.
Solution of the above problem by this keyword
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

//example of this keyword


class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}

Output111 Karan
222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:
Program where this keyword is not required
1. class Student{
2.
int id;
3.
String name;
4.
5.
student(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student e1 = new Student(111,"karan");
12. Student e2 = new Student(222,"Aryan");
13. e1.display();
14. e2.display();
15. }
16. }
Output:111 Karan
222 Aryan

2) this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
1. //Program of this() constructor call (constructor chaining)
2.
3. class Student{
4.
int id;
5.
String name;
6.
Student (){System.out.println("default constructor is invoked");}
7.
8.
Student(int id,String name){
9.
this ();//it is used to invoked current class constructor.
10. this.id = id;
11. this.name = name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student e1 = new Student(111,"karan");
17. Student e2 = new Student(222,"Aryan");
18. e1.display();
19. e2.display();
20. }
21. }
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan

Where to use this() constructor call?


The this() constructor call should be used to reuse the constructor in the constructor. It maintains the
chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below
that displays the actual use of this keyword.

1. class Student{
2.
int id;
3.
String name;
4.
String city;
5.
6.
Student(int id,String name){

7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22. }

this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan","delhi");
e1.display();
e2.display();
}

Output:111 Karan null


222 Aryan delhi

Rule: Call to this() must be the first statement in constructor.


1. class Student{
2.
int id;
3.
String name;
4.
Student (){System.out.println("default constructor is invoked");}
5.
6.
Student(int id,String name){
7.
id = id;
8.
name = name;
9.
this ();//must be the first statement
10. }
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. Student e1 = new Student(111,"karan");
15. Student e2 = new Student(222,"Aryan");
16. e1.display();
17. e2.display();
18. }
19. }
Output:Compile Time Error

3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the this

keyword, compiler automatically adds this keyword while invoking the method. Let's see the example

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}

Output:method is invoked

4) this keyword can be passed as an argument in the method.


The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling. Let's see the example:

1. class S{
2. void m(S obj){
3. System.out.println("method is invoked");
4. }

5.
6.
7.
8.
9.
10.
11.
12.
13.

void p(){
m(this);
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}

Output:method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a class to another one.

5) The this keyword can be passed as argument in the constructor call.


We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple
classes. Let's see the example:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

class B{
A obj;
B(A obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A class
}
}
class A{
int data=10;
A(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A a=new A();
}
}

Output:10

6) The this keyword can be used to return current class instance.


We can return the this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement from the method
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test{
public static void main(String args[]){
new A().getA().msg();
}
}

Output:Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

class A{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A obj=new A();
System.out.println(obj);//prints the reference ID
obj.m();
}
}

Output:A@13d9c02
A@13d9c02

Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of class?

Inheritance is a mechanism in which one object acquires all the properties and behaviours of
parent object.
The idea behind inheritance is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you reuse (or inherit) methods and fields, and
you add new methods and fields to adapt your new class to new situations.
Inheritance represents the IS-A relationship.
Why use Inheritance?

For Method Overriding (So Runtime Polymorphism).


For Code Reusability.

Syntax of Inheritance
1. class Subclass-name extends Superclass-name
2. {
3.
//methods and fields
4. }
The keyword extends indicates that you are making a new class that derives from an existing class. In
the terminology of Java, a class that is inherited is called a superclass. The new class is called a subclass.

Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Output:Programmer salary is:40000.0


Bonus of programmer is:10000

In the above example,Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of Inheritance

On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical.
Multiple and Hybrid is supported through interface only. We will learn about interfaces later.

Multiple inheritance is not supported in java in case of class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Que) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java. For example:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
Usage of super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
1) super is used to refer immediate parent class instance variable.
Problem without super keyword
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

class Vehicle{
int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}

Output:100

In the above example Vehicle and Bike both class have a common property speed. Instance variable of
current class is refered by instance bydefault, but I have to refer parent class instance variable that is
why we use super keyword to distinguish between parent class instance variable and current class
instance variable.

Solution by super keyword


1. //example of super keyword
2.
3. class Vehicle{

4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}

Output:50

2) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor as given below:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
Bike(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}

Output:Vehicle is created
Bike is created

super() is added in each class constructor automatically by compiler.

As we know well that default constructor is provided by compiler automatically but it also adds super()
for the first statement.If you are creating your own constructor and you don't have either this() or
super() as the first statement, compiler will provide super() as the first statement of the constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
int speed;
Bike(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike b=new Bike(10);
}
}

Output:Vehicle is created
10

3) super can be used to invoke parent class method.


The super keyword can also be used to invoke parent class method. It should be used in case subclass
contains the same method as parent class as in the example given below:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

class Person{
void message(){System.out.println("welcome");}
}
class Student extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}
}

Output:welcome to java
welcome

In the above example Student and Person both classes have message() method if we call message()
method from Student class, it will call the message() method of Student class not of Person class
because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the example given
below message() method is invoked from Student class but Student class does not have message()
method, so you can directly call message() method.
Program in case super is not required
1.
2.
3.
4.
5.
6.
7.
8.
9.

class Person{
void message(){System.out.println("welcome");}
}
class Student extends Person{
void display(){
message();//will invoke parent class message() method
}

10.
11.
12.
13.
14.
15.

public static void main(String args[]){


Student s=new Student();
s.display();
}
}

Output:welcome

Вам также может понравиться