0% found this document useful (0 votes)
97 views

Unit-1 Java Notes

java

Uploaded by

mastersin2022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Unit-1 Java Notes

java

Uploaded by

mastersin2022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

LECTURE NOTES
UNIT- I

Syllabus: Object Oriented Programming: Principles, Benefits of Object Oriented Programming.


Introduction to Java: Java buzzwords, bytecode. Java Programming Fundamentals: Applet and
Application program using simple java program, data types, variables, arrays, operators, expressions,
control statements, type conversion and casting, concepts of classes, objects, constructors, methods,
access control, this keyword, garbage collection, overloading methods and constructors, introducing
access control, static, final, nested and inner classes, exploring string class, using command-linear
arguments.Inheritance: Inheritance concept, types of inheritance, Member access rules, use of
super and final. Polymorphism - dynamic binding, method overriding, abstract classes and methods.

Course Objective: To understand fundamentals of object-oriented programming in Java which


includes defining classes, invoking methods, difference between applet and application programs,
using class libraries

Course Outcome: Achieve proficiency in object-oriented concepts and also learns to incorporate the
same into the Java programming language

PRINCIPLES OF OBJECT ORIENCTED PROGRAMMING

Encapsulation: Encapsulation is the mechanism of hiding of data implementation by restricting


access to public methods.
Abstraction: Abstract means a concept or an Idea which is not associated with any particular
instance.
Inheritance: Inheritances expresses is-a and/or has-a relationship between two objects.
Polymorphism: It means one name many forms. It is further of two types static and dynamic.
Static polymorphism is achieved using method overloading and dynamic polymorphism using
method overriding. It is closely related to inheritance. We can write a code that works on the
superclass, and it will work with any subclass type as well.

BENEFITS OF OBJECT ORIENTED PROGRAMMING

 We can build the programs from standard working modules that communicate with one
another, rather than having to start writing the code from scratch which leads to saving of
development.
 OOP language allows to break the program into the bit-sized problems that can be solved
easily (one object at a time).
 The new technology promises greater programmer productivity, better quality of software
and lesser maintenance cost.
 OOP systems can be easily upgraded from small to large systems.
 It is possible that multiple instances of objects co-exist without any interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs which cannot
be invaded by the code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use of existing
classes.

1
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

 Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
 The data-centered design approach enables us to capture more details of model in an
implementable form

JAVA BUZZWORDS

1. Simple
Java was designed to be easy for a professional programmer to learn and use effectively.
It’s simple and easy to learn if you already know the basic concepts of Object Oriented
Programming.
Best of all, if you are an experienced C++ programmer, moving to Java will require very little
effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++,
most programmers have little trouble learning Java.
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
2. Object Oriented
Java is true object-oriented language.
Almost “Everything is an Object” paradigm. All program code and data reside within objects and
classes. The object model in Java is simple and easy to extend. Java comes with an extensive set of
classes, arranged in packages that can be used in our programs through inheritance. Object-oriented
programming (OOPs) is a methodology that simplifies software development and maintenance by
providing some rules.
3. Distributed
Java is designed fa or distributed environment of the Internet. Its used for creating applications on
networks.
Java applications can access remote objects on the Internet as easily as they can do in the local
system.
Java enables multiple programmers at multiple remote locations to collaborate and work together on
a single project.
Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols.
4. Compiled and Interpreted
Usually, a computer language is either compiled or Interpreted. Java combines both this approach
and makes it a two-stage system.
Compiled: Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java Bytecode.
Interpreted: Bytecode is then interpreted, which generates machine code that can be directly
executed by the machine that provides a Java Virtual machine.
5. Robust
It provides many features that make the program execute reliably in a variety of environments.
Java is a strictly typed language. It checks code both at compile time and runtime.
Java takes care of all memory management problems with garbage collection.
Java, with the help of an exception handling, captures all types of serious errors and eliminates any
risk of crashing the system.
6. Secure
Java provides a “firewall” between a networked application and your computer.
When a Java Compatible Web browser is used, downloading can be done safely without fear of
viral infection or malicious intent.
Java achieves this protection by confining a Java program to the Java execution environment and
not allowing it to access other parts of the computer.
7. Architecture Neutral
Java language and Java Virtual Machine helped in achieving the goal of “write once; run anywhere,

2
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
any time, forever.”
Changes and upgrades in operating systems, processors and system resources will not force any
changes in Java Programs.
8. Portable
Java Provides a way to download programs dynamically to all the various types of platforms
connected to the Internet.
It helps in generating Portable executable code.
9. High Performance
Java performance is high because of the use of bytecode.
The bytecode was used so that it was easily translated into native machine code.
10. Multithreaded
Multithreaded Programs handled multiple tasks simultaneously, which was helpful in creating
interactive, networked programs.
Java run-time system comes with tools that support multiprocess synchronization used to construct
smoothly interactive systems.
11. Dynamic
Java is capable of linking in new class libraries, methods, and objects.
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at runtime. This makes it possible to dynamically link code in
a safe and expedient manner.

BYTECODE

Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a .class
file. With the help of java bytecode we achieve platform independence in java.

3
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

APPLET AND APPLICATION PROGRAM USING SIMPLE JAVA PROGRAM

Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
DATA TYPES AND VARIABLES
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
Non-primitive data types: The non-primitive data types include Classes Interfaces and Arrays
A variable is a name assigned to a value that is stored inside the system memory

4
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte

int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Program: Simple.java
import java.io.*;
class Simple{
public static void main(String args[]){
boolean a = true;
byte b = -4;
short c = 2000;
int d = 2345;
long e = 200000L;
float f = 2.00;
double g = 2.0000;
char h = 'D';
System.out.println(a);
System.out.println(b);
}
}
ARRAYS
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.Array in Java is index-based,
the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

5
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

There are two types of array.


 Single Dimensional Array
 Multidimensional Array
Program Testarray.java
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
OPERATORS
Operator in Java is a symbol that is used to perform operations

Operator Type Category Precedence


Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
There are many types of operators in Java
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,

6
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.
Program: operatorexample.java
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
EXPRESSIONS
Expressions are constructed from operands and operators. The operators of an expression indicate
which operations to apply to the operands. The order of evaluation of operators in an expression is
determined by the precedence and associativity of the operators.A Java expression consists of
variables, operators, literals, and method calls. To know more about method calls,
For example:
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
Here, a + b - 3.4 is an expression.
CONTROL STATEMENTS
Java provides statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which provides a
smooth flow of program.
Java provides three types of control flow statements.
1.Decision Making statements
if statements
switch statement

2.Loop statements
do while loop
while loop
for loop
for-each loop
3.Jump statements
break statement
continue statement
program: ifcontrolstatement.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
} } }

7
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
program: switchcontrolstatement.java
public class Student {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
} } }
program: dowhile.java
public class dowhile {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
} }
program: forloop.java
public class forloop {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
} System.out.println("The sum of first 10 natural numbers is " + sum);
} }
program: foreach.java
public class foreach {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
} } }
program: continuedemo.java
public class continuedemo {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
} System.out.println(i);
} } }

8
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

TYPE CONVERSION AND CASTING


In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically. The automatic conversion is done by the compiler and manual
conversion performed by the programmer.

There are two types of type casting:


 Widening Type Casting: Converting a lower data type into a higher one is called widening type
casting.
 Narrowing Type Casting: Converting a higher data type into a lower one is called Narrowing type
casting.
Program: typeconversion.java

public class typeconversion


{
public static void main(String[] args)
{ int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
} }
CONCEPTS OF CLASSES
In object-oriented programming, a class is a basic building block. It can be defined as template that
describes the data and behavior associated with the class instantiation. Instantiating is a class is to
create an object of that class that can be used to access the member variables and methods of the
class.
In general, class declaration includes the following in the order as it appears:
 Modifiers: A class can be public or has default access.
 class keyword: The class keyword is used to create a class.
 Class name: The name must begin with an initial letter (capitalized by convention).
 Superclass (if any): The name of the class's parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
 Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
 Body: The class body surrounded by braces, { }.

9
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Program: simpleclass.java
public class simpleclass{
int x = 5;
public static void main(String[] args) {
simpleclass myObj = new Main();
System.out.println(myObj.x);
}}
OBJECTS
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only. An entity that has state and behavior is known as an object e.g: chair, bike.
An object has three characteristics:
 State: represents the data (value) of an object.
 Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each
object uniquely.

Program: simpleobject.java
public class simpleobject {
int x = 5;
public static void main(String[] args) {
simpleobject myObj = new Main(); // myObj is an object of class simpleobject
System.out.println(myObj.x);
}}
CONSTRUCTORS
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called. It calls a default constructor if
there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.
There are rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
There are two types of constructors in Java:
 Default constructor (no-argument constructor)
 Parameterized constructor
Program Bike1.java
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}}

10
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
METHODS
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a method
once and use it many times. We do not require to write code again and again. It also provides the
easy modification and readability of code, just by adding or removing a chunk of code. The method
is executed only when we call or invoke it.

There are two types of methods in Java:


Predefined Method: predefined methods are the method that is already defined in the Java class libraries.
Example: length(), equals(), compareTo(), sqrt()
User-defined Method: The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.

Program: EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
} }

11
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
ACCESS CONTROL
We can control the access level for class member variables and methods through access specifiers .
Java's access specifiers are public, private, protected and a default access level.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.

class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) {
c = i;
} int getc() {
return c;
}}
public class Main {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 1;
ob.b = 2;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a +
" " + ob.b + " " + ob.getc());
}}
THIS KEYWORD
“this” is a reference variable that refers to the current object.
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.

12
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER

GARBAGE COLLECTION
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.It makes java memory efficient because garbage
collector removes the unreferenced objects from heap memory.It is automatically done by the
garbage collector(a part of JVM) so we don't need to make extra efforts.
Two types of garbage collection activity usually happen in Java. These are:
Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects
in the young generation heap memory are removed.
Major or Full Garbage Collection: It is said to have occurred when the objects that survived the
minor garbage collection are copied into the old generation or permanent generation heap memory
are removed. When compared to the young generation, garbage collection happens less frequently
in the old generation.
OVERLOADING METHODS AND CONSTRUCTORS
Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters or both.
Overloading is related to compile-time (or static) polymorphism.

// Java program to demonstrate working of method overloading in Java.

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}}

13
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Constructor overloading
The constructor overloading can be defined as the concept of having more than one constructor
with different parameters so that every constructor can perform a different task.
Program: Student.java

public class Student {


//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}
STATIC
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
FINAL
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only.
Example:

14
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
NESTED AND INNER CLASSES
Writing a class within another is allowed in Java. The class written within is called the nested
class, and the class that holds the inner class is called the outer class. Nested classes are divided
into two types
 Non-static nested classes (Inner Classes) − These are the non-static members of a class.
 Static nested classes − These are the static members of a class.

Example:
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
} }
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}}
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner(); }}

15
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
STRING CLASS IN JAVA
String is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created.
There are two ways to create string in Java:
 String literal
String s = “matrusri”;
 Using new keyword
String s = new String (“matrusri”);
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Example: StringExample.java
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
COMMAND LINE ARGUMENTS
The java command-line argument is an argument i.e. passed at the time of running the java
program.The arguments passed from the console can be received in the java program and it can
be used as an input.So, it provides a convenient way to check the behavior of the program for the
different values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Example CommandLineExample.java
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}

16
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
INHERITANCE CONCEPT
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Inheritance in java is used:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
TYPES OF INHERITANCE
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.In java programming, multiple and hybrid inheritance is supported through interface
only.

17
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Program:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
MEMBER ACCESS RULES
Superclass members can be inherited to subclass provided they are eligible by access modifiers.
The behavior of access specifiers in the case of inheritance in java is as follows:
1. The private members of the superclass cannot be inherited to the subclass because the private
members of superclass are not available to the subclass directly. They are only available in their
own class.
2. The default members of the parent class can be inherited to the derived class within the same
package.
3. The protected members of a parent class can be inherited to a derived class but the usage of
protected members is limited within the package.
4. Public members can be inherited to all subclasses.
USE OF SUPER AND FINAL
SUPER
The super keyword in Java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.
Program:
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
/* Note that instead of writing num we are writing super.num in the print statement
* this refers to the num variable of Superclass */

18
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
FINAL
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
 variable
 method
 class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only
Program: class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
} }//end of class
POLYMORPHISM - DYNAMIC BINDING
“Dynamic” means “run time”, and “binding” means “association”. So the term dynamic binding
indicates run time association of objects by java virtual machine.
 Dynamic binding occurs during runtime.
 virtual methods are bonded during runtime based upon runtime object.
 dynamic binding uses object to resolve binding.
 overridden methods are bonded using dynamic binding at runtime.
Program:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

19
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
METHOD OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java. In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as Method Overriding.
Java Method Overriding is used for:
 Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Program:
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
} }
ABSTRACT CLASSES AND METHODS
ABSTRACT CLASS
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body). It needs to be extended and its
method implemented. It cannot be instantiated. It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
ABSTRACT METHOD
Abstract method can only be used in an abstract class, and it does not have a body. The body is
provided by the subclass (inherited from)
Program:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run()
{
System.out.println("running safely"); }
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run(); }}

END OF UNIT-I

20

You might also like