Unit - 2 Introduction To Object-Oriented Programming
Unit - 2 Introduction To Object-Oriented Programming
Programming
• Basic concepts of object-oriented programming
• Classes, instances, methods
• Static and non-static members
P
• Packages
•
•
PP
Inheritance and polymorphism, method overriding
Final and abstract classes, abstract methods
• Interfaces
• Generics, enumeration
• Inner classes and anonymous classes
• Class loaders, class path
• Class
Basic Concepts of OOP
– A blueprint/template that describes the behavior/state that
the object of its type support.
– E.g. A class Car that has
• State (Attributes) :: Color, Brand, Weight, Model
• Behaviors (Methods) :: Break, Accelerate, Slow Down, Gear Change
P
– This is just a blueprint, it does not represent any Car, however
using this we can create Car objects (or instances) that represents
the car.
• Object
PP
– It is an instance of class.
– When the objects are created, they inherit all the variables and
methods from the class.
E.g.
– Objects : Audi, Toyota, Volvo, Maruti, Honda
• Class
Basic
: Fruit
Concepts of OOP
• Objects : Orange, Mango, Banana etc.
• Class : Shape
• Objects : Square, Rectangle, Triangle, Circle etc.
P
• Class : Pen
• Objects PP
: Reynold, Parker , Camlin, Luxor etc.
• Class : Bicycle
• Objects : SportsBicycle, MountainBicycle , TouringBicycle etc.
• Class : Department
• Objects : Sales , Purchase, Finance, HR etc.
class Car {
Basic Concepts of OOP
String color;
String brand;
int weight;
String model;
void break() {
//Write code here
P
}
void accelerate() {
}
//Write code herePP
void slow_Down() {
//Write code here
}
void gear_change() {
//Write code here
}
}
Basic Concepts of OOP
• Abstraction
– A process where you show only “relevant” data and “hide”
unnecessary details of an object from the user.
– E.g. The person only knows that pressing the accelerators
will increase the speed of car or applying brakes will stop
the car, but he/she does not know about the inner
P
mechanism of the accelerator, brakes etc in the car.
PP
– E.g. When you login to your bank account online, you
enter your user_id and password and press login, what
happens when you press login, how the input data sent to
server, how it gets verified is all abstracted away from the
you
– In Java, we use abstract class and interface to achieve
abstraction.
Basic Concepts of OOP
• Encapsulation
– Binding object state(fields / attributes) and
behavior(methods) together.
– E.g.
• A Class is an example of encapsulation.
P
• Inform what the object does instead of how it does.
• Keep data and methods safe from outside
PP
interference or misuse.
• Inheritance
Basic Concepts of OOP
– The process by which one class acquires the properties and
functionalities of another class is called inheritance.
– Inheritance provides the idea of reusability of code and each sub
class defines only those features that are unique to it, rest of the
features can be inherited from the parent class.
P
– E.g. A parent class Teacher and a child class MathTeacher. In the
MathTeacher class we need not to write the same code which is
PP
already present in the parent class.
– E.g. In Class Teacher methods are Teacher_Info, Attendance_Info,
Classwork_Video etc.
– E.g. In Class MathTeacher methods are Word_Problems, Patterns.
Basic Concepts of OOP
• Polymorphism
– It allows us to perform a single action in different ways.
P
PP
– E.g. Area of 2D shape :
Formula is different for Rectangle, Square, Triangle
P
data type method-name 1 ( parameter –list 1 ) { body of method }
PP
data type method-name 2 ( parameter –list 1 ) { body of method }
……………………………………………………………………………………………………..
P
E.g.
PP
Integer obj1 = new Integer();
Scanner sc = new Scanner(System.in);
String str1 = new String();
Example of Garbage Collection
Integer obj1 = new Integer (5);
System.out.println(obj1);
P
obj1 = new Integer(6);
PP
System.out.println(“ Integer (5) can be recycled”);
Constructor
•Special method that create and initialize an object of particular
class.
•It has the same name as its class & may accepts arguments.
P
•It does not have return type.
PP
•If you do not declare explicit constructor, Java compiler
automatically generate a default constructor that has no
arguments.
•It does not call directly, it is invoked via the new operator.
class Point2D {
double x ;
double y ;
P
PP
point2D ( ) {
x = 0;
y = 0;
}
}
Parameterized Constructor
class Point2D {
double x ;
double y ;
P
PP
point2D ( double ax , double ay ) {
x = ax ;
y = ay ;
}
}
Constructor Overloaded
class Point2D {
double x ;
double y ;
point2D ( ) {
P
x = 0;
y = 0;
}
PP
point2D ( double ax , double ay ) {
x = ax ;
y = ay ;
}
}
class Point2D {
double x ; Example of
double y ;
Constructor Overloaded
point2D ( ) {
x = 0;
y = 0;
}
P
x = ax ;
y = ay ;
}
PP
displayPointCoordinates ( ) {
System.out.println ( “ X co-ordinate value is :: “ + x ) ;
System.out.println ( “ Y co-ordinate value is :: “ + y ) ;
}
}
Class point2DConstructor {
public static void main ( String args [ ] ) {
Point2D p1 = new Point2D (); p1.displayPointCoordinates()
Point2D p2 = new Point2D ( 3 , 4 ); p2.displayPointCoordinates() ;
}
}
Access Class Member Variables
class Product{
int prod_no;
String prod_name ; }
P
p1.prod_no = 1;
p1.prod_name="Mouse";
PP
System.out.println("P1 object Product No. ::" + p1.prod_no);
System.out.println("P1 object Product Name. ::" + p1.prod_name);
// Set data
void set_data(int p , String p_name) {
P
prod_no = p;
prod_name = p_name;
}
// Get Data
PP
void get_data(){
System.out.println("Product No. : " + prod_no);
System.out.println("Product Name : " + prod_name);
}
}
Set Data & Get Data Method in Class
class Test {
public static void main ( String args[] )
{
Product p1 = new Product();
p1.set_data(1,"Mousse");
P
p1.get_data();
PP
Product p2 = new Product();
p2.set_data(2,"Printer");
p2.get_data();
}
}
Exercise
1. Write a java program to create a class named Rectangle
having member variable length and breadth. Define
various constructors with and without arguments. Also
create two methods area and perimeter.
(Formulas : Area = length * breadth &
Perimeter = 2 * ( length + breadth)
P
PP
2. Write a java program to create a class named Square
having member variable length. Define constructor with
and without arguments. Also create two methods area
and perimeter.
(Formulas : Area = length * length
Perimeter = 4 * ( length )
Exercise
3. Write a java program to create a class named circle having
member variable radius. Also create two methods area
and circumference. Initialize the radius value by
constructor or setRadius() method.
(Formulas : Area = PI * radius * radus &
Circumference = 2 * PI * radius)
P
4. Define a Sphere class with two constructors and one
PP
method. The first form of constructor accepts no
arguments. The second form of constructor accepts only
radius of the sphere. The method is to find the area of
sphere. (Formula: Area of sphere = 4* PI * radius * radius)
5. Declare a three class rectangle, square and triangle. Each
class having two methods perimeter and area. Create an
object of each class & find its area and perimeter. Use
constructor overloading concepts in each classes.
Exercise
6. Write a program to accept two integer numbers and one
operator from the user and according to input data apply
the operation on numbers and display the result. (Hint:
Make a class MathOp having methods for addition,
subtraction, division and multiplication.)
7. Write a program to create a class Employee having two
P
member variables emp_id and emp_name. Also methods
PP
to store input data & retrieve output data. Accepts data
of 5 employees from the user & display in proper format.
8. Write a program to create a class for MathFun having
methods even_odd_check, prime_no_check,
palindrome_check, armstrong_check. Create an object of
class, accept one integer number from the user and list
menu for the above methods and according to user choice
display the proper output.
Exercise
9. Write a program to Arr_operation having two methos
sort_data and search_element. Accept N numbers from
the user and choice of operation.
10. Write a program to create a class MatrixOperation having
three methods Mat_Add, Mat_Sub & Mat_Mul. Accepts
P
two matrice from the user and choice of operation.
PP
11. Create a class of student to store the roll_no, stud_name
and marks of 3 subjects. Accepts the data of 5 students
from the user and display the marksheet in proper format.
12. Create a class of product to store product id, product
name, product price and product quantity. Accepts the
data of N products from the user. Also fetch product
details by passing product id or product price.
Exercise
13. Calculate the net salary of an employee by considering the
parameters called HRA(House rent allowance),
DA(Dearness allowance), GS (Gross salary) and income
tax. Let us assume some parameters.
HRA = 10% of basic salary
P
DA = 73% of basic salary
GS =PP
Income tax =
basic salary + DA + HRA
30% of gross salary
net salary = GS - income tax
Take the input from the user N employees name, id and basic
salary and display output in proper format
Access Modifiers in Java
• There are two types of modifiers in Java: access
modifiers and non-access modifiers.
P
• There are four types of Java access modifiers:
PP
o Private
o Default
o Protected
o Public
P
PP
Protected: The access level of a protected modifier is within
the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.
P
PP
Access Modifiers in Java
1) Private
The private access modifier is accessible only within the class.
E.g. Two classes A and Test.
A class contains private data member and private method.
Accessing these private members from outside the class, so there is a
compile-time error.
P
class A {
private int data=40;
}
PP
private void msg(){System.out.println("Hello java");}
P
private A() { } //private constructor
void msg( ) { System.out.println("Hello java"); }
} PP
public class Test{
public static void main(String args[]) {
A obj=new A(); //Compile Time Error
}
}
Access Modifiers in Java
2) Default
P
•The default modifier is accessible only within package.
PP
•It cannot be accessed from outside the package.
P
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
PP
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Access Modifiers in Java
3) Protected
•The protected access modifier is accessible within package and outside
the package but through inheritance only.
•The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
•It provides more accessibility than the default access modifer.
P
E.g.
PP
•Two packages pack and mypack.
•The A class of pack package is public, so can be accessed from outside
the package.
•msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
Access Modifiers in Java
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
P
//save by B.java
package mypack;
import pack.*;
PP
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Access Modifiers in Java
4) Public
•The public access modifier is accessible everywhere.
•It has the widest scope among all other modifiers.
E.g.
//save by A.java
package pack;
P
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
PP
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); } }
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve
many other functionality.
P
•The final modifier for finalizing the implementations of
PP
classes, methods, and variables.
classname.methodname(args);
classname.variablename;
P
PP
Static Variables & Methods of Integer Class
MIN_VALUE
MAX_VALUE
P
static
static
PP
Integer
String
valueOf ( String s )
toBinaryString ( int i )
static String toOctalString (int i )
static String toHexString (int i)
P
double area = Math.PI * Math.pow (radius,2)
PP
double cf = 2 * Math.PI * radius;
E.g. To access methods of Byte, Short, Integer, Long, Float, Double, Char,
String Class, the object of corresponding class is needed.
P
PP
PP
P
PP
P
class Rectangle Example of Instance Methods
{
private double length = 10.50;
private double width = 20.70;
P
void displayData () {
}
PP
System.out.println("Length : "+ length);
System.out.println("Width : "+ width);
P
• Common static variables in all classes are MIN_VALUE, MAX_VALUE
PP
• Static methods of wrapper classes are used to represent the data in
various format as below.
E.g. toBinaryString ( datatype var)
toBinaryString ( int i )
toOctalString ( double i )
toHexString ( long i )
Wrapper Classes
E.g. To get the value of an Integer Object the intValue() method is used.
P
byte byteValue ( )
short shortValue ( )
int
PP
intValue ( )
long longValue ( )
float floatValue ( )
double doubleValue ( )
String toString ( )
Wrapper Classes
Example
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
P
//Conversion from wrapper class type to primary data type
int i = iOb.intValue();
PP
System.out.println(" Value of i ::" + i);
P
object is automatically extracted (unboxed) from a type
PP
wrapper when its value is needed.
P
• Allow to change the character sequence after string
object created.
PP
• Also provides methods to append or insert characters.
Constructor
StringBuffer( ) : Default capacity is 16 chars.
StringBuffer ( int size ) : Capacity to size of chars.
StringBuffer ( String s ): Capacity is size of s plus 16 chars.
StringBuffer Class
Instance Methods
P
int capacity( )
int length ( ) PP
StringBuffer reverse ( )
char charAt ( int i )
StringBuffer insert ( int i, String str )
StringBuilder Class
StringBuilder:
•The StringBuilder in Java represents a mutable sequence of characters.
•Since the String Class in Java creates an immutable sequence of
characters, the StringBuilder class provides an alternate to String Class,
as it creates a mutable sequence of characters.
•Syntax:
P
StringBuilder str = new StringBuilder();
str.append("GFG");
PP
Difference between String,
Stringbuffer and Stringbuilder
• Immutable objects are instances whose state doesn't change after it
has been initialized.
• The String class is an immutable class whereas StringBuffer and
StringBuilder classes are mutable.
P
E.g.
// concatenate two strings with String
PP
String fullName = firstName.concat(" ").concat(lastName);
P
StringBuffer is to used when StringBuilder is used in a single-
multiple threads are working on threaded environment.
the same String
PP
StringBuffer performance is slower StringBuilder performance is faster
when compared to StringBuilder when compared to StringBuffer
Syntax: Syntax:
StringBuffer var = new StringBuffer(str); StringBuilder var = new StringBuilder(str);
‘this’ Keyword
P
•Allows one constructor to explicitly invoke another
PP
constructor in the same class.
• this (args)
Example of ‘this’ keyword
class Point2D {
double x ;
P
double y ;
PP
point2D ( double x , double y ) {
this.x = x ;
this.y = y ;
}
}
Example of ‘this’ keyword
class Point2D {
double x ;
double y ;
P
point2D ( ) {
}
PP
this ( 0 , 0 );
P
System.out.println("Length : "+ this.length);
System.out.println("Width : "+ this.width);
}
this.area();
void area() {
PP
System.out.println("Area of rectangle : "+ this.length * this.width);
}
public static void main (String args[]) {
Rectangle r = new Rectangle();
r. displayData();
r.setData(11,2.5);
r. displayData();
}
}
Inheritance
• Inheritance allows a software developer to derive a new
class from an existing one
• The existing class is called the parent class, or superclass, or
P
base class
• The derived class is called the child class or subclass.
PP
• As the name implies, the child inherits characteristics of the
parent
• That is, the child class inherits the methods and data
defined for the parent class
• It provides the reusability.
56
Types of Inheritance
• Simple Inheritance
• Multilevel Inheritance
P
• Hierarchical Inheritance
PP
• Multiple Inheritance
57
Defining a Subclass
• Syntax:
– Class subclass-name extends superclass-name
P
{
PP
Body of the class
58
Simple Inheritance
P
Base / Super / Parent Class
PP
Derived / Sub / Child Class
class A1 {
Example of Inheritance
int i , j;
void show() { System.out.println("Value of i and j is :" + i + "," + j); }
}
class B1 extends A1 {
int k;
void display() { System.out.println("Value of k is :" + k); }
P
void sum() { System.out.println("i+j+k" +" " + "is" + " :" + (i+j+k)); }
}
public class Test {
PP
public static void main(String S[]) {
A1 a = new A1(); B1 b = new B1();
a.i = 10; a.j = 20; a.show();
b.i = 5; b.j = 10; b.k = 15; b.show(); b.sum();
}
}
Example of Inheritance
// Child class can not access the members of base class which are defined as private.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
P
}
class B extends A {
int total;
void sum() {
PP
total = i + j; // ERROR, j is not accessible here
}
}
class PrivateInh {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
} }
Multilevel Inheritance
• When a subclass is derived form a derived
class than this mechanism is known as
Multilevel Inheritance.
• Multilevel can go up to the any number of
P
levels.
PP Supar Class
Derived Class
Derived of Derived Class
class A { Example of Multilevel Inheritance
int i,j; // var declaration
void show() // method declaration {
System.out.println("Inside Class A....");
System.out.println("Value of i is :" + i);
System.out.println("Value of j is :" + j);
}
}
P
class B extends A{
int k;
void display() {
PP
System.out.println("Inside Class B....");
System.out.println("Value of i is :" + i);
System.out.println("Value of j is :" + j);
System.out.println("Value of k is :" + k);
}
void sum() {
System.out.println("i+j+k" +" " + "is" + " :" + (i+j+k));
}
}
Example of Multilevel Inheritance
class C extends B
{
int l;
void view()
{
P
System.out.println("Inside Class C....");
System.out.println("Value of i is :" + i);
PP
System.out.println("Value of j is :" + j);
System.out.println("Value of k is :" + k);
System.out.println("Value of l is :" + l);
}
void add()
{
System.out.println("i+j+k+l" +" " + "is" + " :" + (i+j+k+l));
}
}
public class Test { Example of Multilevel Inheritance
public static void main(String S[]) {
A a = new A();
B b = new B();
C c = new C();
P
b.i = 5; b.j = 10; b.k = 15;
b.display();
b.sum();
PP
c.i = 30; c.j = 40; c.k = 50; c.l = 60;
c.view();
c.add();
}
}
Hierarchical Inheritance
P
PP
Example of Hirarchical Inheritance
class A3
{
int i,j; // var declaration
void show() // method declaration
{
System.out.println("Inside Class A....");
System.out.println("Value of i is :" + i);
P
System.out.println("Value of j is :" + j);
}
}
PP
class B3 extends A3 Example of Hirarchical Inheritance (Cont.)
{
int k;
void display()
{
System.out.println("Inside Class B....");
System.out.println("Value of i is :" + i);
P
System.out.println("Value of j is :" + j);
System.out.println("Value of k is :" + k);
}
void sum()
PP
{
System.out.println("i+j+k" +" " + "is" + " :" + (i+j+k));
}
}
class C3 extends A3 Example of Hirarchical Inheritance (Cont.)
{
int l;
void view()
{
System.out.println("Inside Class C....");
P
System.out.println("Value of i is :" + i);
System.out.println("Value of j is :" + j);
}
PP
System.out.println("Value of l is :" + l);
void add()
{
System.out.println("i+j+l" +" " + "is" + " :" + (i+j+l));
}
}
public class Hierarchical {
public static void main(String S[]) Example of Hirarchical
{ Inheritance (Cont.)
A3 a=new A3();
B3 b=new B3();
C3 c=new C3();
a.i=10; a.j=20;
P
a.show();
b.i=5;
b.display();
PP b.j=10; b.k=15;
b.sum();
P
PP
• In java multiple inheritance is achieved through the use of
interfaces.
P
• It used for following two purpose:
– To call super class constructor
PP
– To access a member of the super class that has been
hidden by a member of a subclass
Example of ‘super’ Keyword
class A {
private double l = 10 ;
private double b = 20 ; }
Class B extends A
{
P
double area ()
{ double ans = super.l * super.b; }
}
class Test {
PP
public static void main(String args[]) {
B b1 = new B();
System.out.println(“Area :: " + b1.area();
}
}
Polymorphism
• Allows to define one interface and have
multiple implementation.
P
• Types of polymorphism
PP
1) Method Overloading
2) Method Overriding
Method Overloading
• Two or more methods of same name in a class, provided that
there argument list or parameters are different. This concept
is known as Method Overloading.
P
simply executes the version of the method whose parameters
match the arguments used in the call.
PP
• The parameters may differ in their type or number, or in both.
P
double demo(double a) {
System.out.println("double a: " + a); return a*a; }
} PP
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); } }
Method Overriding
• Child class has the same method as of base class.
In such cases child class overrides the parent
class method. This feature is known as method
overriding.
P
PP
• Applies only to inherited methods
• Object type (NOT reference variable type)
determines which overridden method will be
used at runtime
public class BaseClass {
public void methodToOverride() {
System.out.println ("I'm the method of BaseClass"); }
}
P
System.out.println ("I'm the method of DerivedClass"); }
}
PP
public class Test {
public static void main (String args []) {
BaseClass obj1 = new BaseClass();
BaseClass obj2 = new DerivedClass();
obj1.methodToOverride();
obj2.methodToOverride(); }
}
Abstract Class
• Abstract class is used to declare functtionality that
is implemented by one or more subclasses.
P
how that functionality is provided.
PP
• Abstract class can not be instantiated but you can
declare as an object type.
P
}
class S extends T {
void emptymethod() {
}
PP
System.out.println(“ Implementation of emptymethod.");
}
class Test {
public static void main(String args[]) {
T b = new S();
b. emptymethod();
b. concretemethod();
} }
Example of Abstract Class
Create an abstract class Shape with constructor
to display the object name. It has two abstract
methods area() and perimeter(). Also one non-
abstract method moveTo (x , y) to move object at
specific co-ordinate. Create a class Rectangle
P
with constructor having three parameters length,
PP
width and name. Also it overrides method area()
and perimeter(). Create another class Circle with
constructor having two parameters radius and
name. Also it overrides method area() and
perimeter().
Final Class
• Final class cannot be extended.
P
overridden.
PP
• The compiler gives an error if you attempt to extend a
final class.
P
• It is group of constants and method declaration.
PP
• An interface can be used as type of variable. The
variable can then reference any object that implements
that interface.
P
mathModifier1 type1 mthName1(params 1);
………………….
PP
mathModifierN typeN mthNameN(params N);
}
P
• Abstract methods
PP
Interface contains
• Only abstract methods.
P
In Interface all methods are public & abstract & variable are
PP
public static final.
P
An interface can extend another Java interface only.
PP
• Example of abstract class:
public abstract class Shape {
public abstract void perimeter(); }
Example of interface
public interface Shape {
void perimeter(); }
Generics
• Introduce in JDK 5.
• It is possible to create classes, interfaces and methods
that will work in a type-safe manner with various kinds
of data.
E.g. The mechanism that supports a stack is the same
P
whether that stack is storing items of type Integer, Float,
PP
Double, String, Object or Thread.
• With generic you can define an algorithm once,
independently of any specific type of data, and than
apply that algorithm to a wide variety of data type
without any additional effort.
• With generics, all casts are automatic and implicit,
which expands the ability to reuse code and easily.
Java Generic Type
• Usually type parameter names are single, uppercase
letters to make it easily distinguishable from java
variables. The most commonly used type parameter
names are:
• E – Element
P
• K – Key
• N – Number PP
• T – Type
• V – Value
• S,U,V etc. – 2nd, 3rd, 4th types
Generic Method Example
// A Simple Java program to make a program of generic
classes
// We use < > to specify Parameter type
class Gclass <T> {
// An object of type T is declared
P
T obj;
PP
Gclass ( T obj ) {
this.obj = obj; }
public T getObject() {
return this.obj; }
}
Generic Method Example
public class Test {
public static void main (String[] args) {
// instance of Integer type
P
Gclass <Integer> iObj = new Gclass<Integer>(15);
System.out.println( iObj.getObject() );
PP
// instance of String type
Gclass <String> sObj = new Gclass<String>("GeeksForGeeks");
System.out.println( sObj.getObject() );}
}
Generic Method Example
E.g. Print an array of different type using a single
Generic method
public class GenericMethodTest {
// generic method printArray
P
public static < E > void printArray( E[] inputArray ) {
PP
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
Generic Method Example
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
P
System.out.println("Array integerArray contains:");
PP
printArray(intArray); // pass an Integer array
P
• An enumeration can have constructors,
PP
methods and instance variable.
• Methods
– public static enum-type [ ] values ()
– public static enum-type valueOf (String str)
Example of Enumeration
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
P
//printing all enum
for (Season s : Season.values()){
PP
System.out.println(s); }
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is:
"+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is:
"+Season.valueOf("SUMMER").ordinal()); } }
Inner class
• Inner class or nested class is a class which is declared
within a class.
• It is used to logically group classes and interfaces in one
place so that it can be more readable and maintainable.
class Test{
P
private int data=30;
PP
class Inner {
void msg(){System.out.println("data is "+data); } }
public static void main(String args[]){
Test obj = new Test();
Test.Inner in = obj.new Inner();
in.msg(); } }
ClassLoader in Java
• The Java ClassLoader is a part of the Java Runtime
Environment that dynamically loads Java classes into
the Java Virtual Machine.
• Java classes aren’t loaded into memory all at once, but
when required by an application.
P
• At this point, the Java ClassLoader is called by the JRE and
these ClassLoaders load classes into memory dynamically.
PP
• Depending on the type of class and the path of class, the
ClassLoader that loads that particular class is decided.
• To know the ClassLoader that loads a class the
getClassLoader() method is used.
• All classes are loaded based on their names and if any of
these classes are not found then it returns a
NoClassDefFoundError or ClassNotFoundException.
Class Path in Java
• We don't need to set PATH and CLASSPATH to compile and
run java program while using IDE like Netbeans.
• These environment variables are required
to compile and run java program using CMD (Command
prompt)
P
• System will understand java command with the help of
PATH variable and find class using CLASSPATH variable to
run it. PP
Set Path Variable
To compile & run java program in any directory the path of java bin
directory set into the path environment variable as below.
P
Windows
Select Start, select Control Panel. double click System
PP
Select the Advanced tab.
Click Environment Variables.
In the section System Variables, find the PATH environment variable &
Select it. Click Edit.
At the end of line add path of Bin Directory.