Week 1-2 - Java Language-Merged

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Object Oriented Programming – JAVA LANGUAGE

JAVA LANGUAGE
History of Java Programming Language

Java is an Object-Oriented programming language developed by James Gosling in the


early 1990s. The team initiated this project to develop a language for digital devices such as
set-top boxes, television, etc. Originally C++ was considered to be used in the project but the
idea was rejected for several reasons(For instance C++ required more memory). Gosling
endeavoured to alter and expand C++ however before long surrendered that for making
another stage called Green. James Gosling and his team called their project “Greentalk” and
its file extension was .gt and later became to known as “OAK”.
Why “Oak”?

The name Oak was used by Gosling after an oak tree that remained outside his office.
Also, Oak is an image of solidarity and picked as a national tree of numerous nations like the
U.S.A., France, Germany, Romania, etc. But they had to later rename it as “JAVA” as it was
already a trademark by Oak Technologies.
“JAVA”
Gosling and his team did a brainstorm session and after the session, they
came up with several names such as JAVA, DNA, SILK, RUBY, etc.
Java name was decided after much discussion since it was so unique. The name Java
originates from a sort of espresso bean, Java. Gosling came up with this name while having a
coffee near his office. Java was created on the principles like Robust, Portable, Platform
Independent, High Performance, Multithread, etc. and was called one of the Ten Best
Products of 1995 by the TIME MAGAZINE.
Currently, Java is used in internet programming, mobile devices, games, e-business
solutions, etc. The Java language has experienced a few changes since JDK 1.0 just as various
augmentations of classes and packages to the standard library. In Addition to the language
changes, considerably more sensational changes have been made to the Java Class Library
throughout the years, which has developed from a couple of hundred classes in JDK 1.0 to
more than three thousand in J2SE 5.

1|P age
Object Oriented Programming – JAVA LANGUAGE

History of various Java versions:


RELEASE

VERSION DATE MAJOR CHANGES

JDK

Beta 1995

January The Very first version was released on January 23, 1996. The

JDK 1.0 1996 principal stable variant, JDK 1.0.2, is called Java 1.

Was released on February 19, 1997. There were many additions in

JDK 1.1 as compared to version 1.0 such as

 A broad retooling of the AWT occasion show


February  Inner classes added to the language
 JavaBeans
JDK 1.1 1997  JDBC
 RMI

“Play area” was the codename which was given to this form and

was released on 8th December 1998. Its real expansion included:

strictfp keyword

 the Swing graphical API was coordinated into the centre


classes
December  Sun’s JVM was outfitted with a JIT compiler out of the blue
 Java module
J2SE 1.2 1998  Java IDL, an IDL usage for CORBA interoperability
 Collections system

Codename- “KESTREL”

Release Date- 8th May 2000

Additions:

 HotSpot JVM included


 Java Naming and Directory Interface
 JPDA
J2SE 1.3 May 2000  JavaSound
 Synthetic proxy classes

2|P age
Object Oriented Programming – JAVA LANGUAGE

RELEASE

VERSION DATE MAJOR CHANGES

Codename- “Merlin”

Release Date- 6th February 2002

Additions: Library improvements

 Regular expressions modelled after Perl regular expressions


 The image I/O API for reading and writing images in formats
like JPEG and PNG
 Integrated XML parser and XSLT processor (JAXP) (specified
in JSR 5 and JSR 63)
February
 Preferences API (java.util.prefs)
Public Support and security updates for this version ended in
J2SE 1.4 2002
October 2008.

Codename- “Tiger”

Release Date- “30th September 2004”

Originally numbered as 1.5 which is still used as its internal

version. Added several new language features such as:

September  for-each loop


 Generics
J2SE 5.0 2004  Autoboxing
 Var-args

Codename- “Mustang”

Released Date- 11th December 2006

Packaged with a database supervisor and encourages the

utilization of scripting languages with the JVM. Replaced the

name J2SE with ava SE and dropped the .0 from the version

number.

Additions:

JAVA SE December  Upgrade of JAXB to version 2.0: Including integration of a


StAX parser.
6 2006  Support for pluggable annotations (JSR 269).
 JDBC 4.0 support (JSR 221)

3|P age
Object Oriented Programming – JAVA LANGUAGE

RELEASE

VERSION DATE MAJOR CHANGES

Codename- “Dolphin”

Release Date- 7th July 2011

Added small language changes including strings in the switch. The

JVM was extended with support for dynamic languages.

Additions:
JAVA SE
 Compressed 64-bit pointers.
7 July 2011  Binary Integer Literals.
 Upstream updates to XML and Unicode.

Released Date- 18th March 2014

JAVA SE Language level support for lambda expressions and default

8 March 2014 methods and a new date and time API inspired by Joda Time.

Release Date: 21st September 2017

Project Jigsaw: designing and implementing a standard, a module

JAVA SE September system for the Java SE platform, and to apply that system to the

9 2017 platform itself and the JDK.

Released Date- 20th March

Addition:

 Additional Unicode language-tag extensions


 Root certificates
JAVA SE  Thread-local handshakes
 Heap allocation on alternative memory devices
10 March 2018  Remove the native-header generation tool – javah.
 Consolidate the JDK forest into a single repository.

Released Date- 25th September, 2018


JAVA SE September
Additions-
11 2018
 Dynamic class-file constants

4|P age
Object Oriented Programming – JAVA LANGUAGE

RELEASE

VERSION DATE MAJOR CHANGES

 Epsilon: a no-op garbage collector


 The local-variable syntax for lambda parameters
 Low-overhead heap profiling
 HTTP client (standard)
 Transport Layer Security (TLS) 1.3
 Flight recorder

Released Date- 19th March 2019

Additions-

 Shenandoah: A Low-Pause-Time Garbage Collector


(Experimental)
 Microbenchmark Suite
JAVA SE  Switch Expressions (Preview)
 JVM Constants API
12 March 2019  One AArch64 Port, Not Two
 Default CDS Archives

JAVA TECHNOLOGY

The Java Development Kit (JDK) is one of three core technology packages used in Java
programming, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment). It's important to differentiate between these three technologies, as well as
understanding how they're connected:

 The JVM is the Java platform component that executes programs.


 The JRE is the on-disk part of Java that creates the JVM.
 The JDK allows developers to create Java programs that can be executed and
run by the JVM and JRE.

Developers new to Java often confuse the Java Development Kit and the Java Runtime
Environment. The distinction is that the JDK is a package of tools for developing Java-based
software, whereas the JRE is a package of tools for running Java code.

The JRE can be used as a standalone component to simply run Java programs, but it's
also part of the JDK. The JDK requires a JRE because running Java programs is part of
developing them.

5|P age
Object Oriented Programming – JAVA LANGUAGE

Figure 1 shows how the JDK fits into the Java application development lifecycle.

Used to
JDK Create a
Java
JVM
Program Compiled
Java
Java
Program
JRE Program Run
inside

Used to execute Java Program

Figure 1. High-level view of the JDK

Just as we did with my recent introduction to the Java Virtual Machine, let's consider the
technical and everyday definitions of the JDK:

 Technical definition: The JDK is an implementation of the Java platform


specification, including compiler and class libraries.
 Everyday definition: The JDK is a software package you download in order to
create Java-based applications.

The JDK & the Java compiler

In addition to the JRE, which is the environment used to run Java applications, every
JDK contains a Java compiler. The compiler is the software program capable of taking raw
.java files--which are plain text--and rendering them into executable .class files. We'll see the
compiler in action soon. First, I'll show you how to download and setup a JDK in your
development environment.

Features of Java

The primary objective of Java programming language creation was to make it


portable, simple and secure programming language. Apart from this, there are also some
excellent features which play an important role in the popularity of this language. The features
of Java are also known as java buzzwords.

6|P age
Object Oriented Programming – JAVA LANGUAGE

A list of most important features of Java language is given below.

Figure 2. Features of Java

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.

7|P age
Object Oriented Programming – JAVA LANGUAGE

 There is no need to remove unreferenced objects because there is an Automatic


Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Figure 3. Platform Independent

8|P age
Object Oriented Programming – JAVA LANGUAGE

Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a program
runs.

There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere(WORA).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:

 No explicit pointer
 Java Programs run inside a virtual machine sandbox

Figure 4. Virtual Machine Sandbox

9|P age
Object Oriented Programming – JAVA LANGUAGE

 Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which


is used to load Java classes into the Java Virtual Machine dynamically. It adds security
by separating the package for the classes of the local file system from those that are
imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
 Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust

Robust simply means strong. Java is robust because:

 It uses strong memory management.


 There is a lack of pointers that avoids security problems.
 There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
 There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent


features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.

10 | P a g e
Object Oriented Programming – JAVA LANGUAGE

High-performance

Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in Java.


RMI and EJB are used for creating distributed applications. This feature of Java makes us able
to access files by calling the methods from any machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java


programs that deal with many tasks at once by defining multiple threads. The main advantage
of multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.

Dynamic

Java is a dynamic language. It supports dynamic loading of classes. It means classes


are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage


collection).

HELLO WORLD APPLICATION

1. Write the source code: HelloWorld.java

public class HelloWorld{


public static void main( String args[] ){
System.out.println(“Hello world”);
}
}

11 | P a g e
Object Oriented Programming – JAVA LANGUAGE

Figure 5. Hello World Program

2. Compile: javac HelloWorld.java


3. Run: java HelloWorld

Figure 6. Hello World Write, Compile, Run

Sources

Bhatnagar G. (n.d.). The Complete History of Java Programming Language


https://www.geeksforgeeks.org/the-complete-history-of-java-programming-language/

Features of Java
https://www.javatpoint.com/features-of-java

Tyson, M. (2018). What is Java?


https://www.javaworld.com/article/3296360/what-is-the-jdk-introduction-to-the-java-
development-kit.html

History of Java Programming Languages


https://www.freejavaguide.com/history.html

12 | P a g e
Object Oriented Programming
OOP Concepts

MODULE 2 - Object Oriented Programming Concepts

This module will guide you on what is a class and how does Java deal with objects.
You will know how to create a class and instantiate its object. These are the basic building
blocks of object-oriented programming (OOP) in Java.

At the end of this module, the student should be able to:

1. Identify classes and objects in java


2. Understand the concept of encapsulation in java
3. Write constructors in java program
4. Define packages used in java

Object-Oriented Programming
Many time you must have come across the phrase Java is an Object-Oriented
Programming Language. The term Object-Oriented denotes a concept in software
development.

It is a way of organizing software in the form of objects that contain both data and the
behavior of these objects. Therefore, Object-Oriented Programming Languages, generally
known as OOP, provide the programming model for simplifying for software development,
design and maintenance under some well-established ground rules.

The projects made in OOPS are more structured towards objects. As a result, it
increases performance, maintainability, and development of the program. The main idea
behind OOP is to incorporate data and behavior under the same location(objects).

Class in Java
A class in Java or any other Object-oriented Language is a blueprint for objects to
follow a specific schema defined in the class.

Classes define the behavior for objects of its type. It represents a collection of
properties (data and functions) for all its objects.

It supports a template for creating objects which bind code and data. Further,
classes act as a means to define methods and data. It helps in maintaining access
specifications for member variables using access specifiers.

Object in Java
An Object is the most fundamental entity in Java or any other Object-Oriented
Language. Objects represent real-life entities because each of them could have specific
behavior, identity, and data (attributes).

In Java, the object is an offspring of its class. The class has properties to reflect the
object state and methods to represent the behavior.

The methods also show an object’s response to other objects. Identity is a unique
name for the object assigned by the user, much like variables.

1|P age
Object Oriented Programming
OOP Concepts

Let’s have a profound look into what are objects. If we think about this present
reality, we can discover numerous articles around us, vehicles, people, and so on. Every one
of these has a unique state and behavior. You can’t expect a human being to bark like a dog
or a dog to speak like a human.

For example – A car, its state are – name, model no, shade, manufacturer and its behavior
can be – moving, blinking the headlights, honking, etc.
If you try to compare a Java object with any real-time entity, they could probably have
fundamentally same attributes.

public class Car {


// Class Attributes – State of an object

String color;
Int model_no;
String name;
String manf;

// Class Methods – Behavior of an object


void brake(){
}

void accelerate(){
}

void turn(){
}
}

A class can have any number of functions to access the properties of the class’s object or
manipulate the properties. In the above example, move(), blink() and honk() are a few methods.

Variable Types:
A class can contain any of the accompanying variable sorts:

Class Variables:
A class variable is one which has the static keyword as a prefix in its declaration. Its
definition occurs only inside a class and outside any function.

Local Variables:
These are variables which have declarations inside methods, constructors or blocks.
They are local to the part of the code they belong.

Local variables come into existence when the control enters into the code block that
keeps their declaration. And they vanish with the block leaving out of execution.

Instance Variables:
These variables are inside a class however outside any method. They come into
existence when the class instantiates. These are accessible from any constructor or block of
that specific class.

2|P age
Object Oriented Programming
OOP Concepts

Access Modifiers

Java supports four access modifiers that you can use to define the visibility of classes,
methods, and attributes. Each of them specifies a different level of accessibility, and you can
only use one modifier per class, method or attribute. As a rule of thumb, you should always
use the most restrictive modifier that still allows you to implement your business logic.

These modifiers are, starting from the most to the least restrictive one:

 private
 no modifier
 protected
 public

Let’s take a closer look at each of these modifiers and discuss when you should use them.

Private
This is the most restrictive and most commonly used access modifier. If you use
the private modifier with an attribute or method, it can only be accessed within the same
class. Subclasses or any other classes within the same or a different package can’t access this
attribute or method.

As a rule of thumb, the private modifier should be your default choice for all attributes and
internal methods that shouldn’t be called from external classes. You might need to make an
exception to this rule when you’re using inheritance, and some of the subclasses need direct
access to an attribute or internal method. In that case, you should use the protected modifier
instead of private.

No modifier
When you don’t provide any access modifier for your attribute or method, you can access it
within your class and from all classes within the same package. That’s why it’s often called
package-private.

Protected
Attributes and methods with the access modifier protected can be accessed within your class,
by all classes within the same package, and by all subclasses within the same or other
packages.

The protected modifier gets mostly used for internal methods that need to be called or
overridden by subclasses. You can also use it to allow subclasses to access internal attributes
of a superclass directly.

Public
This is the least restrictive access modifier. Methods and attributes that use
the public modifier can be accessed within your current class and by all other classes.

Public methods and attributes become part of the public API of your class and of any
component in which you include them. That is almost never a good idea for any attribute, and
you should think twice before you use this modifier on a method.

3|P age
Object Oriented Programming
OOP Concepts

If a method is publicly available, you need to make sure that it’s well documented and that it
robustly handles any input values. Also keep in mind, that sooner or later this method will be
used by some part of your application that will make it hard to change or remove it.

Here you can see an overview of the different access modifiers and the accessibility of the
attributes or methods.

Encapsulation

simply means binding object state(fields) and behaviour(methods) together. If you are
creating class, you are doing encapsulation. In this guide we will see how to do encapsulation
in java program, if you are looking for a real-life example of encapsulation then refer this
guide: OOPs features explained using real-life examples.

What is encapsulation?

The whole idea behind encapsulation is to hide the implementation details from users. If a
data member is private it means it can only be accessed within the same class. No outside
class can access private data member (variable) of other class.

However if we setup public getter and setter methods to update (for example void setSSN(int
ssn))and read (for example int getSSN()) the private data fields then the outside class can
access those private data fields via public methods.

This way data can only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known as data
hiding. Lets see an example to understand this concept better.

Example of Encapsulation in Java

How to implement encapsulation in java:

1) Make the instance variables private so that they cannot be accessed directly from outside
the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.

4|P age
Object Oriented Programming
OOP Concepts

class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;

//Getter and Setter methods


public int getEmpSSN(){
return ssn;
}

public String getEmpName(){


return empName;
}

public int getEmpAge(){


return empAge;
}

public void setEmpAge(int newValue){


empAge = newValue;
}

public void setEmpName(String newValue){


empName = newValue;
}

public void setEmpSSN(int newValue){


ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:

Employee Name: Mario


Employee SSN: 112233
Employee Age: 32
In above example all the three data members (or data fields) are private(see: Access Modifiers in Java)
which cannot be accessed directly. These fields can be accessed via public methods only.
Fields empName, ssn and empAge are made hidden data fields using encapsulation technique of
OOPs.

Advantages of encapsulation

1. It improves maintainability and flexibility and re-usability: for e.g. In the above code the
implementation code of void setEmpName(String name) and String getEmpName() can be
changed at any point of time. Since the implementation is purely hidden for outside classes

5|P age
Object Oriented Programming
OOP Concepts

they would still be accessing the private field empName using the same methods
(setEmpName(String name) and getEmpName()). Hence the code can be maintained at any
point of time without breaking the classes that uses the code. This improves the re-usability of
the underlying class.
2. The fields can be made read-only (If we don’t define setter methods in the class) or write-only
(If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) that
we don’t want to be changed so we simply define the variable as private and instead of set and
get both we just need to define the get method for that variable. Since the set method is not
present there is no way an outside class can modify the value of that field.
3. User would not be knowing what is going on behind the scene. They would only be knowing
that to update a field call set method and to read a field call get method but what these set and
get methods are doing is purely hidden from them.

Encapsulation is also known as “data Hiding“.

What is a Constructor?

Constructor looks like a method but it is in fact not a method. It’s name is same as
class name and it does not return any value. You must have seen this statement in almost all
the programs I have shared above:

MyClass obj = new MyClass();


If you look at the right side of this statement, we are calling the default constructor of
class myClass to create a new object (or instance).

We can also have parameters in the constructor, such constructors are known
as parametrized constructors.
Example of constructor
public class ConstructorExample {

int age;
String name;

//Default constructor
ConstructorExample(){
this.name="Chaitanya";
this.age=30;
}

//Parameterized constructor
ConstructorExample(String n,int a){
this.name=n;
this.age=a;
}
public static void main(String args[]){
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 =
new ConstructorExample("Steve", 56);
System.out.println(obj1.name+" "+obj1.age);
System.out.println(obj2.name+" "+obj2.age);
}
}

6|P age
Object Oriented Programming
OOP Concepts

A package as the name suggests is a pack(group) of classes, interfaces and other packages. In java we
use packages to organize our classes and interfaces. We have two types of packages in Java: built-in
packages and the packages we can create (also known as user defined package). In this guide we will
learn what are packages, what are user-defined packages in java and how to use them.

In java we have several built-in packages, for example when we need user input, we import a package
like this:

import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

Before we see how to create a user-defined package in java, lets see the advantages of using a
package.

Advantages of using a package in Java

These are the reasons why you should use packages in Java:

 Reusability: While developing a project in java, we often feel that there are few things that
we are writing again and again in our code. Using packages, you can create such things in
form of classes inside a package and whenever you need to perform that same task, just
import that package and use the class.
 Better Organization: Again, in large java projects where we have several hundreds of classes,
it is always required to group the similar types of classes in a meaningful package name so
that you can organize your project better and when you need something you can quickly
locate it and use it, which improves the efficiency.
 Name Conflicts: We can define two classes with the same name in different packages so to
avoid name collision, we can use packages

Types of packages in Java

As mentioned in the beginning of this guide that we have two types of packages in java.
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as
built-in packages.

We have already discussed built-in packages, lets discuss user-defined packages with the
help of examples.

Example 1: Java packages

I have created a class Calculator inside a package name letmecalculate. To create a class inside
a package, declare the package name in the first statement in your program. A class can have
only one package declaration. Calculator.java file created inside a package letmecalculate

7|P age
Object Oriented Programming
OOP Concepts

package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Now lets see how to use this package in another program.

import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
To use the class Calculator, I have imported the package letmecalculate. In the above program I have
imported the package as letmecalculate.Calculator, this only imports the Calculator class. However if
you have several classes inside package letmecalculate then you can import the package like this, to
use all the classes of this package.

import letmecalculate.*;
Example 2: Creating a class inside package while importing another package

As we have seen that both package declaration and package import should be the first statement in
your java program. Lets see what should be the order when we are creating a class inside a package
while importing another package.

//Declaring a package
package anotherpackage;
//importing a package
import letmecalculate.Calculator;
public class Example{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
So the order in this case should be:
→ package declaration
→ package import

Example 3: Using fully qualified name while importing a class

You can use fully qualified name to avoid the import statement. Lets see an example to understand
this:
Calculator.java

package letmecalculate;

8|P age
Object Oriented Programming
OOP Concepts

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Example.java

//Declaring a package
package anotherpackage;
public class Example{
public static void main(String args[]){
//Using fully qualified name instead of import
letmecalculate.Calculator obj =
new letmecalculate.Calculator();
System.out.println(obj.add(100, 200));
}
}
In the Example class, instead of importing the package, I have used the full qualified name such
as package_name.class_name to create the object of it. You may also want to read: static import in
Java

Sub packages in Java

A package inside another package is known as sub package. For example If I create a package inside
letmecalculate package then that will be called sub package.

Lets say I have created another package inside letmecalculate and the sub package name is multiply.
So if I create a class in this subpackage it should have this package declaration in the beginning:

package letmecalculate.multiply;
Multiplication.java

package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;
}
}
Now if I need to use this Multiplication class I have to either import the package like this:

import letmecalculate.multiply;
or I can use fully qualified name like this:

letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();

9|P age
Object Oriented Programming
OOP Concepts

Points to remember:

1. Sometimes class name conflict may occur. For example: Lets say we have two
packages abcpackage and xyzpackage and both the packages have a class with the same name, let it
be JavaExample.java. Now suppose a class import both these packages like this:

import abcpackage.*;
import xyzpackage.*;
This will throw compilation error. To avoid such errors you need to use the fully qualified name
method that I have shown above. For example

abcpackage.JavaExample obj = new abcpackage.JavaExample();


xyzpackage.JavaExample obj2 = new xyzpackage.JavaExample();
This way you can avoid the import package statements and avoid that name conflict error.

2. I have already discussed this above, let me mention it again here. If we create a class inside a
package while importing another package then the package declaration should be the first
statement, followed by package import. For example:

package abcpackage;
import xyzpackage.*;
3. A class can have only one package declaration but it can have more than one package import
statements. For example:

package abcpackage; //This should be one


import xyzpackage;
import anotherpackage;
import anything;
4. The wild card import like package.* should be used carefully when working with subpackages. For
example: Lets say: we have a package abc and inside that package we have another package foo,
now foo is a subpackage.

classes inside abc are: Example1, Example 2, Example 3


classes inside foo are: Demo1, Demo2

So if I import the package abc using wildcard like this:

import abc.*;
Then it will only import classes Example1, Example2 and Example3 but it will not import the classes
of sub package.

To import the classes of subpackage you need to import like this:

import abc.foo.*;
This will import Demo1 and Demo2 but it will not import the Example1, Example2 and Example3.

So to import all the classes present in package and subpackage, we need to use two import
statements like this:

10 | P a g e
Object Oriented Programming
OOP Concepts

import abc.*;
import abc.foo.*;

Sources

Agarwal, M. (n.d.). Class and Object in Java - OOPs.


https://www.techbeamers.com/java-class-object/

Janssen, T. (2017). OOP Concept for Beginners: What is Encapsulation


https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/

Singh, C. (2013). Encapsulation in java with example.


https://beginnersbook.com/2013/05/encapsulation-in-java/

11 | P a g e
Object Oriented Programming
Inheritance and Polymorphism

MODULE 3 – Inheritance and Polymorphism

At the end of this module, the student should be able to:

1. Define inheritance and polymorphism.


2. Identify the parent class and child class
3. Write a program using inheritance and polymorphism.

What is Inheritance?

The process by which one class acquires the properties (data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance is to provide
the reusability of code so that a class has to write only the unique features and rest of the common
properties and functionalities can be extended from the another class.

Child Class:

The class that extends the features of another class is known as child class, sub class or derived
class.

Parent Class:

The class whose properties and functionalities are used(inherited) by another class is known as
parent class, super class or Base class.

Inheritance is a process of defining a new class based on an existing class by extending its common
data members and methods. Inheritance allows us to reuse of code, it improves reusability in your
java application.

Note: The biggest advantage of Inheritance is that the code that is already present in base class
need not be rewritten in the child class.

This means that the data members(instance variables) and methods of the parent class can be
used in the child class as.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC


{
}
Inheritance Example

In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since
class PhysicsTeacher extends the designation and college properties and work() method from
base class, we need not to declare these properties and method in sub class.
Here we have collegeName, designation and work() method which are common to all the teachers
so we have declared them in the base class, this way the child classes
like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be
used directly from base class.

1|P ag e
Object Oriented Programming
Inheritance and Polymorphism

class Teacher {
String designation = "Teacher";
String collegeName = "John";
void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:

John
Teacher
Physics
Teaching
Based on the above example we can say that PhysicsTeacher IS-A Teacher. This means that a child
class has IS-A relationship with the parent class. This inheritance is known as IS-A
relationship between child and parent class

Note:
The derived class inherits all the members and methods that are declared as public or protected.
If the members or methods of super class are declared as private then the derived class cannot
use them directly. The private members can be accessed only in its own class. Such private
members can only be accessed using public or protected getter and setter methods of super class
as shown in the example below.

class Teacher {
private String designation = "Teacher";
private String collegeName = "John";
public String getDesignation() {
return designation;
}
protected void setDesignation(String designation) {
this.designation = designation;
}
protected String getCollegeName() {
return collegeName;
}
protected void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
void does(){
System.out.println("Teaching");
}
}

public class JavaExample extends Teacher{

2|P ag e
Object Oriented Programming
Inheritance and Polymorphism

String mainSubject = "Physics";


public static void main(String args[]){
JavaExample obj = new JavaExample();
/* Note: we are not accessing the data members
* directly we are using public getter method
* to access the private members of parent class
*/
System.out.println(obj.getCollegeName());
System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);
obj.does();
}
}
The output is:

John
Teacher
Physics
Teaching
The important point to note in the above example is that the child class is able to access the private
members of parent class through protected methods of parent class. When we make a instance
variable(data member) or method protected, this means that they are accessible only in the class
itself and in child class. These public, protected, private etc. are all access specifiers and we will
discuss them in the coming tutorials.

Constructors and Inheritance

constructor of sub class is invoked when we create the object of subclass, it by default invokes
the default constructor of super class. Hence, in inheritance the objects are constructed top-
down. The superclass constructor can be called explicitly using the super keyword, but it should
be first statement in a constructor. The super keyword refers to the superclass, immediately
above of the calling class in the hierarchy. The use of multiple super keywords to access an
ancestor class other than the direct parent is not permitted.
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
}
class JavaExample extends ParentClass{
JavaExample(){
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
System.out.println("Constructor of Child");
}
public static void main(String args[]){
//Creating the object of child class
new JavaExample();
}
}

3|P ag e
Object Oriented Programming
Inheritance and Polymorphism

Output:

Constructor of Parent
Constructor of Child
Inheritance and Method Overriding

When we declare the same method in child class which is already present in the parent class the
this is called method overriding. In this case when we call the method from child class object, the
child class version of the method is called. However we can call the parent class method using
super keyword as I have shown in the example below:
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
void disp(){
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
System.out.println("Constructor of Child");
}
void disp(){
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[]){
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The output is :

Constructor of Parent
Constructor of Child
Child Method
Parent Method

WHAT IS POLYMORPHISM?

Polymorphism is one of the OOPs feature that allows us to perform a single action in
different ways. For example, lets say we have a class Animal that has a method sound().
Since this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc.
We had to give a generic message.

public class Animal{


...
public void sound(){
System.out.println("Animal is making a sound");
}
}

4|P ag e
Object Oriented Programming
Inheritance and Polymorphism

Now lets say we two subclasses of Animal class: Horse and Cat that extends Animal class. We can
provide the implementation to the same method like this:

public class Horse extends Animal{


...
@Override
public void sound(){
System.out.println("Neigh");
}
}
and

public class Cat extends Animal{


...
@Override
public void sound(){
System.out.println("Meow");
}
}
As you can see that although we had the common action for all subclasses sound() but there
were different ways to do the same action. This is a perfect example of polymorphism (feature
that allows us to perform a single action in different ways). It would not make any sense to
just call the generic sound() method as each Animal has a different sound. Thus we can say
that the action this method performs is based on the type of object.

What is polymorphism in programming?

Polymorphism is the capability of a method to do different things based on the object that it
is acting upon. In other words, polymorphism allows you define one interface and have
multiple implementations. As we have seen in the above example that we have defined the
method sound() and have the multiple implementations of it in the different-2 sub classes.
Which sound() method will be called is determined at runtime so the example we gave above
is a runtime polymorphism example.

Lets write down the complete code of it:

Example 1: Polymorphism in Java

Runtime Polymorphism example:


Animal.java

public class Animal{


public void sound(){
System.out.println("Animal is making a sound");
}
}
Horse.java

class Horse extends Animal{


@Override
public void sound(){

5|P ag e
Object Oriented Programming
Inheritance and Polymorphism

System.out.println("Neigh");
}
public static void main(String args[]){
Animal obj = new Horse();
obj.sound();
}
}
Output:

Neigh
Cat.java

public class Cat extends Animal{


@Override
public void sound(){
System.out.println("Meow");
}
public static void main(String args[]){
Animal obj = new Cat();
obj.sound();
}
}
Output:

Meow
Example 2: Compile time Polymorphism

Method Overloading on the other hand is a compile time polymorphism example.

class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}

6|P ag e
Object Oriented Programming
Inheritance and Polymorphism

}
Here the method demo() is overloaded 3 times: first method has 1 int parameter, second method
has 2 int parameters and third one is having double parameter. Which method is to be called is
determined by the arguments we pass while calling methods. This happens at runtime compile time
so this type of polymorphism is known as compile time polymorphism.

Output:

a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25

Sources

Singh, C. (2013). Encapsulation in java with example.


https://beginnersbook.com/2013/05/encapsulation-in-java/

Singh, C. (2013). Encapsulation in java with example.

https://beginnersbook.com/2013/03/polymorphism-in-java/

7|P ag e

You might also like