0% found this document useful (0 votes)
3 views55 pages

Java PRG - Intr, Classes, Inheriance, Interface

The document provides an overview of Java programming, detailing its features such as object-oriented design, platform independence, and security. It covers the history of Java, its usage across various applications, and key concepts like classes, inheritance, and interfaces. Additionally, it discusses Java's syntax, data types, and the importance of access control and modifiers.

Uploaded by

rajkumarm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views55 pages

Java PRG - Intr, Classes, Inheriance, Interface

The document provides an overview of Java programming, detailing its features such as object-oriented design, platform independence, and security. It covers the history of Java, its usage across various applications, and key concepts like classes, inheritance, and interfaces. Additionally, it discusses Java's syntax, data types, and the importance of access control and modifiers.

Uploaded by

rajkumarm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

RAMAKRISHNA MISSION VIDYALAYA

DIGITAL LEARNING MATERIAL

JAVA PROGRAMMING

Dr.N.BASKAR

ASSISTANT PROFESSOR IN COMPUTER SCIENCE

SRI RAMAKRISHNA MISSION VIDYALAYA COLLEGE OF ARTS AND SCIENCE


COIMBATORE – 641 020
Introduction
01 .

What is Java?
02
Why use
03 Java
History of 04
Setting Path Java
05
Classes 06
07 Inheritance

Interface 08
Introduction

Java programming language was originally developed by


Sun Microsystems which was initiated by James Gosling and
released in 1995
Java runs on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX
• Java is guaranteed to be Write Once, Run Anywhere.
What is Java?

• Java is −
• Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
• Platform Independent − when Java is compiled, it is not compiled into platform
specific machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
• Simple − Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master.
• Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
• Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
What is Java?
• Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable.
• Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
• Multithreaded − With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultaneously.
• Interpreted − Java byte code is translated on the fly to native machine instructions
and is not stored anywhere.
• High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
• Distributed − Java is designed for the distributed environment of the internet.
• Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment.
Why Use Java?
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming language in the world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of developers)
• Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
• As Java is close to C++ and C#, it makes it easy for programmers to switch to
Java or vice versa
Why Use Java?
It is owned by Oracle, and more than 3 billion devices run Java.
J2SE for Java Standard Edition, J2EE for Enterprise Application Edition, J2ME
for Mobile Application Edition
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
History of Java
• James Gosling initiated Java language project in June 1991 for use in one of
his many set-top box projects. The language, initially called ‘Oak’ after an
oak tree that stood outside Gosling's office, also went by the name ‘Green’
and ended up later being renamed as Java, from a list of random words.
• Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once, Run Anywhere (WORA), providing no-cost run-times
on popular platforms.
• On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
• On 8 May, 2007, Sun finished the process, making all of Java's core code free
and open-source, aside from a small portion of code to which Sun did not
hold the copyright.
Popular Java Editors

• Notepad − On Windows machine, you can use any simple text editor like
Notepad, TextPad,etc.,
• Netbeans − A Java IDE that is open-source and free which can be
downloaded from https://www.netbeans.org/index.html.
• Eclipse − A Java IDE developed by the eclipse open-source community and
can be downloaded from https://www.eclipse.org/
Definition : Object, Class, Methods, Instance
• Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
• Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
• Methods − A method is basically a behavior. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.
• Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
Setting permanent path
Setting permanent path
Java Compiler
Java Translation
• The Java compiler translates Java source code into a
special representation called bytecode

• Java bytecode is not the machine language for any


traditional CPU

• Another software tool, called an interpreter, translates


bytecode into machine language and executes it

• Therefore the Java compiler is not tied to any particular


machine

• Java is considered to be architecture-neutral


Syntax and Example

public class classname Example:


{ public class abc
public static void main (String arg[ ]) {
{
// Statements public static void main(String ab[])
} {
System.out.println("Welcome");
}
}
Java Enums
 Enums were introduced in Java 5.0. class FreshJuice
 Enums restrict a variable to have one of { enum FreshJuiceSize{ SMALL,
MEDIUM, LARGE }
only a few predefined values. FreshJuiceSize size;
 The values in this enumerated list are }
called enums. public class FreshJuiceTest
{ public static void main(String args[])
 With the use of enums it is possible to {
reduce the number of bugs in code FreshJuice juice = new FreshJuice();
juice.size =
FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}
Access Control Modifiers

• Java provides a number of access modifiers to set access levels for classes,
variables, methods and constructors. The four access levels are −
• Visible to the package, the default. No modifiers are needed.
• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses (protected).
Non-Access Modifiers

• Java provides a number of non-access modifiers to achieve many other


functionality.
• The static modifier for creating class methods and variables.
• The final modifier for finalizing the implementations of classes, methods,
and variables.
• The abstract modifier for creating abstract classes and methods.
• The synchronized and volatile modifiers, which are used for threads.
Data types
Classes
• An object is defined by a class
• A class is the blueprint of an object
• The class uses methods to define the behaviors of the object
• The class that contains the main method of a Java program represents the
entire program

• A class represents a concept, and an object represents the embodiment of


that concept

• Multiple objects can be created from the same class


Classes
• 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 initialized when the class is
instantiated. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
• Class variables − Class variables are variables declared within a class,
outside any method, with the static keyword.
Classes - program

class rectangle
class rectareas
{int length,width; {public static void main(String ab[])
void getdata(int x,int y) {int a1,a2;
{length=x; rectangle rect1=new rectangle();
width=y; rectangle rect2=new rectangle();
} rect1.length=5;
int rectarea() rect1.width=10;
{int area=length*width; a1=rect1.length*rect1.width;
return(area); rect2.getdata(10,10);
} a2=rect2.rectarea();
} System.out.println("Area 1= "+a1);
System.out.println("Area 2= "+a2);
Inheritance
• Inheritance is the mechanism of deriving new class from old one, old
class is knows as superclass and new class is known as subclass.
• The subclass inherits all of its instances variables and methods defined by
the superclass and it also adds its own unique elements.
• Thus we can say that subclass are specialized version of superclass.
• Benefits of Java’s Inheritance
• Reusability of code
• Code Sharing
• Consistency in using an interface
Inheritance
Superclass(Base Class) Subclass(Child Class)
It is a class from which other It is a class that inherits some or
classes can be derived. all members from superclass.
The super keyword is similar to this keyword following are the scenarios where the super
keyword is used.

It is used to differentiate the members of superclass from the members of subclass, if they
have same names.

super.variable
super.method();

It is used to invoke the superclass constructor from subclass.


Single Inheritance

extends is the keyword used to inherit the properties of a class.


Syntax :
class Super
{
.....
.....
}
class Sub extends Super{
.....
.....
}
Single Inheritance: Program
class Shape { public class Tester {
public void display() {
public static void main(String[]
System.out.println("Inside display");
arguments) {
}
} Rectangle rect = new Rectangle();
class Rectangle extends Shape { rect.display();
public void area() {
System.out.println("Inside area"); rect.area();
} }
}
}
Multilevel Inheritance
• Multilevel Inheritance – It is a ladder or hierarchy of single level inheritance.
It means if Class A is extended by Class B and then further Class C extends
Class B then the whole structure is termed as Multilevel Inheritance.
Syntax
class A{
//Do something
}
class B extends A{
//Do something
}
class C extends B{
//Do something
}
Multilevel Inheritance : Program
class Shape {
public void display() { public class Tester {
System.out.println("Inside display"); public static void main(String[] arguments) {
}} Cube cube = new Cube();
class Rectangle extends Shape { cube.display();
public void area() { cube.area();
System.out.println("Inside area"); cube.volume();
}} }
class Cube extends Rectangle { }
public void volume() {
System.out.println("Inside volume");
}
}
Hierarchical Inheritance

• Hierarchical Inheritance - one class is extended by many subclasses. It is


one- to-many relationship
Hierarchical Inheritance : Syntax

Class A{ Class MainClass{


public void methodA(){ public void methodB(){
//Do Something //Do Something
}} }
public static void main(String args[]){
Class B extends A{
B obj1 = new B();
public void methodB(){
C obj2 = new C();
//Do Something obj1.methodA();
}} obj2.methodA();
Class C extends A{ }
public void methodC(){ }

//Do Something
Hierarchical Inheritance : Program
//A.java //MainClass.java
class HierarchicalInheritance { class HierarchicalInheritanceMain {
void DisplayA() { public static void main(String args[]) {
System.out.println("This is a content of parent class");
System.out.println("Calling
}}
for child class C");
//B.java
B b = new B();
class A extends HierarchicalInheritance {
void DisplayB() { b.DisplayA();
System.out.println("This is a content of child class 1"); b.DisplayC();
}} System.out.println("Calling for
//c.java child class B");
class B extends HierarchicalInheritance {
A a = new A();
void DisplayC() {
a.DisplayA();
System.out.println("This is a content of child class 2");
a.DisplayB();
}}
}
super Keyword

• super is a reference variable that is used to refer immediate parent class


object. Uses of super keyword are as follows:
• super() is used to invoke immediate parent class constructors
• super is used to invoke immediate parent class method
• super is used to refer immediate parent class variable
super keyword : Example

To print the value of Base class variable in a child class use


super.variable name

This “i” will print value of local class


variable

Output:
call Immediate Parent Class Constructor
using super Keyword
• The super() keyword can be used to invoke the Parent class constructor
Method Overriding
• 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.
Method Overriding : Program
class sub extends Super class overrides
class Super
{ { {
int x; int y; public static void
Super(int x) sub (int x,int y) main(String ab[])
{ { {
this.x=x;
super(x); sub s1=new sub(10,20);
}
this.y=y; s1.display();
void display()
{ }
}
System.out.println( " Super void display( )
}
class x=" +x); {
} System.out.println(" super x = "
} +x);
System.out.println(" super y =
" +y );
}}
Final Keyword

• Final keyword can be used in the following ways:


• Final Variable : Once a variable is declared as final, its value cannot be
changed during the scope of the program
• Final Method : Method declared as final cannot be overridden
• Final Class : A final class cannot be inherited
Final variable : Program
Variable “i” is declared as final

In this code we are trying to modify the value of a Final Variable wh


error as shown in the output
Final method : Program
Final Class : Program

Output
Abstract Classes
• When the keyword abstract appears in a class definition, it means that zero or
more of its methods are abstract.
• An abstract method has no body.
• Some of the subclass has to override it and provide the implementation.
• Objects cannot be created out of abstract class.
• Abstract classes basically provide a guideline for the properties and methods
of an object.
• In order to use abstract classes, they have to be subclassed.
• There are situations in which you want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation
of every method.
Abstract Classes : Program
Interface

• An interface in Java is a blueprint of a class. It has static constants and


abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Why use Java interface?
• There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
• Syntax:
• interface <interface_name>
• { // declare constant fields
• // declare methods that abstract
• // by default.
•}
Interface : Program
interface printable{
void print();
}
class A6 implements printable{
public void print()
{System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
Multiple Inheritance(Interface): Program

interface Printable{
void print(); }
interface Showable{
void show(); }
class A7 implements Printable,Showable {
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print(); obj.show(); } }
Interface inheritance
A class implements an interface, but one
interface extends another interface. class TestInterface4 implements Showable{
Example: public void print()
{System.out.println("Hello");}
interface Printable{ public void show()
void print(); {System.out.println("Welcome");}
} public static void main(String args[]){
interface Showable extends Printable{ TestInterface4 obj = new TestInterface4();
void show(); obj.print();
} obj.show();
}
}
Default Method in Interface
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
Static Method in Interface

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Interface : Lab program
interface area
class circle implements area
{
{public float compute(float x,float y)
final static float pi=3.14f;
{ return(pi*x*x); } }
float compute(float x,float y);
class testinterface
}
{ public static void main(String ab[])
class rectangle implements area
{ rectangle r1=new rectangle();
{
circle c1=new circle();
public float compute(float x,float y)
area a1; a1=r1;
{
System.out.println(“Rectangle Area="+a1.compute(10,10))
return(x*y);
a1=c1;
}
System.out.println("Area of circle= "+a1.compute(10,5));
}
Nested Interface
• An interface can have another interface which is known as a nested interface
Syntax
interface printable
{ void print();
interface MessagePrintable{
void msg();
}
}
Java Input Statement
Java provides different ways to get input from the user.
To get input from user using the object of Scanner class.
In order to use the object of Scanner, we need to
import java.util.Scanner package.
Syntax:
// create an object of Scanner
Scanner input = new Scanner(System.in);
// take input from the user
int number = input.nextInt();
Java Input Statement
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
// closing the scanner object
input.close();
}
Java Input Statement
// Getting double input
import java.util.Scanner; System.out.print("Enter double: ");
class Input { double myDouble = input.nextDouble();
public static void main(String[] args) { System.out.println("Double entered = " +
myDouble);
Scanner input = new Scanner(System.in);
// Getting String input
// Getting float input System.out.print("Enter text: ");
System.out.print("Enter float: "); String myString = input.next();
float myFloat = input.nextFloat(); System.out.println("Text entered = " + myString);
System.out.println("Float entered = " + }
myFloat); }

Getting input from keyboard : Output

You might also like