UNIT 3 Part 1

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

UNIT-3

UNIT-III
Single Inheritance: Inheritance & types of Inheritance – C++, Type Substitutability;
Inheritance & types of Inheritance - Java, Type Substitutability; Method Overriding & super
keyword, type casts – C++ and Java, this & final, access-specifiers in C++ and java. Static
Polymorphism using inheritance – C++.

1. Inheritance:
The capability of a class to derive properties and characteristics from another class
is called Inheritance. Inheritance is one of the most important features of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class
or Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base
Class or Super class.
Structure: Example:

ACCESS SPECIFIERS AND SIMPLE INHERITANCE


We have 3 different types of access specifiers private, public and protected.

 The public members of a class can be accessed by an object directly outside the class.
Directly means when objects access the data member without the member function of
the class.
 The private members of the class can only be accessed by the public member function
of the same class.
 The protected access specifier is the same as private. The only difference is that it
allows its derived classes to access the protected members directly without the member
functions.

 The derived class (sub class) is indicated by associating with the base class. A new
class also has its own set of member variables and functions.
 The names of the derived and base classes are separated by a colon(:). The access
specifiers may be private or public. In the absence of an access specifier, the default
is private.

Page 1
UNIT-3

Reusability:
Reusability means the reuse of properties of the base class in the derived classes. Reusability
permits the reuse of members of the previous class. We can add extra features in the existing
class. This is possible by creating a new class from the existing class. The new class will have
the features of both the old and the derived new class. In Figure (Inheritances), the base class
is reused. Reusability is achieved using inheritance. Inheritance and reusability are not
different from each other. The outcome of inheritance is reusability.

Types of inheritance
 Single inheritance
 Multiple inheritance
 Hierarchical inheritance
 Multilevel inheritance
 Hybrid inheritance
 Multi-path inheritance

1.Single inheritance:
This occurs when only one base class is used for the derivation of a derived class, such a
type of inheritance that has one base and derived class is known as single inheritance.
A derived class inherits data member variables and functions of the base class. However
constructors and destructors of base class are not inherited in the derived class

Single Inheritance Syntax:


class A // base class
{
..........
};
class B : acess_specifier A // derived class
{
...........
};

Page 2
UNIT-3

Example 1: Write a program to show single inheritance.


#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter the value of x = ";
cin >> x;
}
};
class derive : public base //single derived class
{
private:
int y;
public:
void readdata()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};
int main()
{
derive a; //object of derived class
a.getdata();
a.readdata();
a.product();
return 0;
}
Output:
Enter the value of x = 3
Enter the value of y = 4
Product = 12
Example 2: Write a program to show single inheritance between two classes.
#include<iostream>
class ABC
{
protected: char name[15];
Page 3
UNIT-3

int age;
};
class abc : public ABC // public derivation
{
float height;
float weight;
public:
void getdata()
{
cout«"\n Enter Name and Age:";
cin»name»age;
cout«"\n Enter Height and Weight:";
cin»height »weight;
}
void show()
{
cout«"\n Name:"«name «"\n Age:"«age«" Years";
cout<<" \ n Height : " «height «" Feet s" « " \ n Weight : " «weight «"K g.";
}
};
int main()
{
abc x;
x.getdata(); // Reads data through keyboard.
x.show(); // Displays data on the screen.
return 0;
}

Output:
Enter Name and Age : Santosh 24
Enter Height and Weight : 4.5 50
Name : Santosh
Age : 24 Years
Height : 4.5 Feets Weight : 50 Kg.

2.Multiple Inheritance
When two or more base classes are used for the derivation of a class, it is called multiple
inheritance. A class can be derived by inheriting the properties of more than one class.
Properties of various pre-defined classes are transferred to a single derived class.

Page 4
UNIT-3

Syntax: multiple inheritance


class A
{
..........
};
class B
{
...........
};
class C : acess_specifier A,access_specifier A // derived class from A and B
{
...........
};
Example 1: write a c++ program on multiple inheritance
#include<iostream>
using namespace std;
class A
{
public:
int x;
void getx()
{
cout << "enter value of x: ";
cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "enter value of y: ";
cin >> y;
}
};
class C : public A, public B

Page 5
UNIT-3

{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};
int main()
{
C obj1;
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
}
Output:
enter value of x: 5
enter value of y: 4
Sum = 9
Example 2: Write a program to derive a class from multiple base classes using protected
specifier.
#include<iostream.h>
class A {protected: int a;}; // class A declaration
class B {protected: int b;}; // class B declaration
class C {protected: int c;}; // class C declaration
class D {protected: int d;}; // class D declaration
class E : public A, public B, public C, public D or class E : public A,B,C,D
{
int e;
public:
void getdata()
{
cout«"\n Enter values of a,b,c & d & e:";
cin»a»b»c»d»e;
}
void showdata()
{
cout<<" \n a="«a «" b=" «b «" c = "«c «" d= "«d «" e="«e;
}
};
int main()
{
E x;
x.getdata(); // Reads data
Page 6
UNIT-3

x.showdata(); // Displays data


return 0;
}
Output:
Enter values of a,b,c & d & e : 1 2 4 816
a=1 b=2c=4d=8z=16
3. Hierarchical Inheritance
When a single base class is used for the derivation of two or more classes, it is
known as hierarchical inheritance.

Hierarchical Inheritance Syntax:


class A // base class
{
..............
};
class B : access_specifier A // derived class from A
{
...........
};
class C : access_specifier A // derived class from A
{
...........
};
class D : access_specifier A // derived class from A
{
...........
};
Example 1: write a c++ program on hierarchical inheritance
#include <iostream>
using namespace std;
class A //single base class
{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n";
cin >> x >> y;
}

Page 7
UNIT-3

};
class B : public A //B is derived from class base
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
int main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}
Example 2: Write a program to show hierarchical inheritance using constructor.
#include<iostream.h>
class red {
public:
red() {
cout«"Red";
}
};
class yellow {
public:
yellow() {
cout«"Yellow";
}
};
class blue {
public:
blue() {
Page 8
UNIT-3

cout«"Blue";
}
};
class orange : public red, public yellow
{
public:
orange()
{
cout«"Mixing of red, yellow = Orange";
}
};
class violet : public red, public blue
{
public:
violet()
{
cout«"Mixing of red, blue=Violet";
}
};
class reddishbrown: public orange, public violet
{
public:
reddishbrown()
{
cout«"Mixing of orange, violet = Reddishbrown";
}
int main()
{
reddishbrown r;
return 0;
}
Output:
Red
Yellow
Mixing of red, yellow = Orange
Red
Blue
Mixing of red, blue=Violet
Mixing of orange, violet = Reddishbrown

4. Multilevel Inheritance
When a class is derived from another derived class, that is, the derived class acts as
a base class, such a type of inheritance is known as multilevel inheritance.
Page 9
UNIT-3

Multilevel Inheritance Syntax:


class A // base class
{
...........
};
class B : acess_specifier A // derived class
{
...........
};
class C : access_specifier B // derived from derived class B
{
...........
};
Example 1: c++ program on multilevel inheritance
#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter value of x= ";
cin >> x;
}
};
class derive1 : public base // derived class from base class
{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= ";
cin >> y;
}
};
class derive2 : public derive1 // derived from class derive1

Page 10
UNIT-3

{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= ";
cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
int main()
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
}
Output:
Enter value of x= 2
Enter value of y= 3
Enter value of z= 3
Product= 18
Example 2: c++ program on multilevel inheritance
#include<iostream>
using namespace std;
class Al // Base class
{
protected:
char name[15];
int age;
};
class A2 : public Al // Derivation first level
{
protected:
float height;
float weight;
};
class A3 : public A2 // Derivation second level
Page 11
UNIT-3

{
protected:
char gender;
public:
void get() // Reads data
{
cout«"Name:";
cin»name;
cout«"Age:";
cin»age;
cout«"Gender:";
cin»gender;
cout«"Height:";
cin»height;
cout«"Weight:";
cin»weight;
void show() // Displays data
{
cout«"\nName:" «name;
cout«"\nAge:" «age «" Years";
cout«"\nGender:" «gender;
cout«"\nHeight:" «height «" Feets";
cout«"\nWeight:" «weight «" Kg.";
};
int main()
{
A3 x; // Object Declaration
x.get(); // Reads data
x.show(); // Displays data
return 0;
}
Output:
Name: ABC
Age: 23
Gender: M
Height: 4
Weight: 50
Name: XYZ
Age: 45
Gender: F
Height: 5
Weight: 67
5. Hybrid inheritance:
A combination of one or more types of inheritance is known as Hybrid inheritance.
Page 12
UNIT-3

Hybrid Inheritance Syntax:


class A
{
.........
};
class B : public A
{
..........
};
class C
{
...........
};
class D : public B, public C
{
...........
};
Example 1: write a c++ program on hybrid inheritance
#include <iostream>
using namespace std;
class A
{
public:
int x;
};
class B : public A
{
public:
B() //constructor to initialize x in base class A
{
x = 10;
}
};

Page 13
UNIT-3

class C
{
public:
int y;
C() //constructor to initialize y
{
y = 4;
}
};
class D : public B, public C //D is derived from class B and class C
{
public:
void sum()
{
cout << "Sum= " << x + y;
}
};
int main()
{
D obj1; //object of derived class D
obj1.sum();
return 0;
}
Output :
Sum= 14
Example 2:
class Student
{
protected:
char name[15];
char gender;
int age;
};
class Height : public Student
{
protected:
float height;
float weight;
};
class Address{
protected:
char city[10];
};
class Details: public Height, Address
Page 14
UNIT-3

{
protected:
char hobby[15];
public:
void getdata()
{
cout«"Enter Following Information\n";
cout«"Name:";
cin»name;
cout«"Gender:";
cin»gender;
cout«"Age:";
cin»age;
cout«"Height:";
cin»height;
cout«"Weight:";
cin»weight;
cout«"City:";
cin»city;
cout«"Hobby:";
cin»hobby;
}
void show() {
cout«"\n Entered Information";
cout«"\nName:";
cout«name;
cout«"\nGender:";
cout«gender;
cout«"\nAge:";
cout«age;
cout«"Height:";
cout«height;
cout«"Weight:";
cout«weight;
cout«"City:";
cout«city;
cout«"Hobby:";
cout«"hobby;
}
};
int main()
{
Details D;
D.getdata();
Page 15
UNIT-3

D,show();
return 0;
}
Output:
Enter Following Information
Name : ABC
Gender : M
Age : 25
Height : 4.9
Weight : 55
City : VZM
Hobby : Cricket
Entered Information
Name : XYZ
Gender : F
Age : 25
Height : 4.9
Weight : 55
City : Vizag
Hobby: Singing
6.Multipath inheritance:
When a class is derived from two or more classes, those are derived from the same
base class. Such type of inheritance is known as Multipath inheritance. This type of inheritance
also consists of many types of inheritance such as multilevel, multiple and hierarchical.

2. Type Substitutability

A virtual function in C++ is declared in the base class but may be overridden by derived
classes. It makes it feasible to treat objects from different derived classes equally by using a
base class-provided common interface by allowing polymorphism and dynamic dispatch.

Page 16
UNIT-3

The virtual function is declared by the base class using the virtual keyword, and it can be
overridden by derived classes using the same function signature along with the override
keyword. Virtual functions are frequently called via base class pointers or references, which
allows the correct function implementation to be invoked based on the actual object type at
runtime. This approach encourages code reuse, extensibility, and flexibility in object-oriented
programming.

#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() const {
std::cout << "Drawing a shape..." << std::endl;
}
};
class Rectangle : public Shape {
public:
virtual void draw() const override {
std::cout << "Drawing a rectangle..." << std::endl;
}
};
int main() {
Shape* shapePtr = new Rectangle();
shapePtr->draw();
delete shapePtr;
return 0;
}

Java:
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound...");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking...");
}
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound();
}
Page 17
UNIT-3

3. Inheritance & types of Inheritance – Java


Deriving new classes from existing classes such that the new classes acquire all the features
of existing classes is called inheritance. The class which inherits the properties of other is
known as subclass (derived class, child class) and the class whose properties are inherited
is known as superclass (base class, parent class). extends is the keyword used to inherit the
properties from one class to another class.
Syntax:
class SuperClass
{
..................
..................
}
class SubClass extends SuperClass
{
..................
..................
}

Types of Inheritance:

There are three types of inheritance in java.


1. Single Inheritance:
Producing sub classes from one super class is called single inheritance.

class B extends A
2. Multilevel Inheritance:
When a class extends a class, which extends anther class then this is called
multilevel inheritance.

Page 18
UNIT-3

Example: Write a JAVA Program to illustrate multilevel inheritance


class A
{
void show()
{
System.out.println("Method A");
}
}
class B extends A
{
void show()
{
super.show(); System.out.println("Method B");
}
}
class C extends B
{
void show()
{
super.show(); System.out.println("Method C");
}
}
class MultiLevel
{
public static void main(String[] args)
{
C c1=new C(); c1.show();
}
}
3. Hierarchical Inheritance:

class A
{
public void methodA()
{
System.out.println(" class A method");

Page 19
UNIT-3

}
}

class B extends A
{
public void methodB()
{
System.out.println(" class B method");
}
}
class C extends A
{
public void methodC()
{
System.out.println(" class C method");
}
public static void main(String args[])
{
B b=new B();
C c = new C();
b.methodA();
b.methodB();
c.methodA();
c.methodC();
}
}

4. Method Overriding
If derived class defines same function as defined in its base class, it is known as
function overriding in C++. It is used to achieve runtime polymorphism.

Example:

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}

Page 20
UNIT-3

};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main() {
Dog d = Dog();
d.eat();
return 0;
}

5. The ‘super’ Keyword:

If we create an object to super class, we can access only the super class members,
but not the sub class members. But if we create sub class object, all the members of both
super and sub classes are available to it. This is the reason; we always create an object to
sub class in inheritance. Sometimes, the super class members and sub class members may
have same names. In that case, by default only sub class members are accessible.

To access super class members and methods by using “super‟ keyword.


 super can be used to refer super class variables, as:
super.variableName
 super can be used to refer super class methods, as:
super.methodName()
 super can be used to refer super class constructor.
We need not to call default constructor of the super class, as it is by default
available to sub class. To call parameterized constructor, we can write:
super(values)

Variable and Method using Super

Example: Write a program to access the super class method and instance variable by using
super keyword from sub class.
class One
{
int i=10; void show()
{
System.out.println("Super Class Method i: "+i);
}
}

Page 21
UNIT-3

class Two extends One


{
int i=20; void show()
{
System.out.println("Sub Class Method i: "+i); super.show();
System.out.println("Super Class Variable i: "+super.i);
}
}
class Demo{
public static void main( String args[] )
{
Two t=new Two(); t.show();
}
}
Output:
Sub Class Method i: 20
Super Class Method i: 10
Super Class Variable i: 10

Super Constructor
Example: Write a program to access parameterized constructor of the super class can be
called from sub class using super keyword.
class One
{
int i; One(int i)
{
this.i=i; this.i=this.i+2;
}
}
class Two extends One
{
int i; Two(int i)
{
super(i); this.i=i;
System.out.println("Sub Class Variable i: "+i); System.out.println("Super Class Variable i:
"+super.i);
}
}
class Demo{
public static void main( String args[] )
{
Two t=new Two(5);
}
}
Page 22
UNIT-3

6. final keyword:

The final keyword in java is used to restrict the user. The java final keyword can
be used in many contexts. Final can be:

a) variable
b) method
c) 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.
1. Final variable
Example:
class Bike9{
final int speedlimit=90;//final variable void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
2. Final method
Example:
class Bike{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();

Page 23
UNIT-3

honda.run();
}
}
3. Final class
Example:
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){ Honda1 honda= new Honda1();
honda.run();
}
}
7. Polymorphism:
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Types of Polymorphism:
i) Compile-time Polymorphism.
ii) Runtime Polymorphism.
i) Compile-Time Polymorphism: It is type of polymorphism is achieved by function
overloading or operator overloading.
ii)Runtime Polymorphism : This type of polymorphism is achieved by Function
Overriding. Late binding and dynamic polymorphism are other names for runtime
polymorphism. The function call is resolved at runtime in runtime polymorphism.
8. Virtual Destructors in C++:
A Virtual Destructor in C++ is used to release the memory space which is allocated by
the derived class object while deleting the object of the derived class using a base class
pointer object.
If we write virtual keyword before base class destructor, then even though the pointer
is of Base class and object is of Derived class and when the object is deleted then first, the
destructor of Derived class will be called and then the destructor of Base class will be called.
[Destructors:
when an object of the derived class is created. first Base constructor executed then Derived
class. First, the destructor of the Derived class will be called then the destructor of the
Base class will be called.]

Page 24
UNIT-3

Example:
#include <iostream>
using namespace std;
class Base
{
public:
Base ()
{
cout << "Base Class Constructor" << endl;
}
virtual ~Base ()
{
cout << "Base Class Destructor" << endl;
}
};
class Derived:public Base
{
public:
Derived ()
{
cout << "Derived Class Constructor" << endl;
}
~Derived ()
{
cout << "Derived Class Destructor" << endl;
}
};
int main()
{
Base *p = new Derived();
delete p;
return 0;
}
Output:
base constructor

Page 25
UNIT-3

derived constructor
derived destructor
base destructor
9. C++ Composition
Composition is an alternative to the class inheritance (is a relationship) that serves
different purposes. In composition, the models have a “has a relationship”.
In real-life complex objects are often built from smaller and simpler objects.
Example
A personal computer is built from a CPU, a motherboard, memory unit, input and output
units, etc. even human beings are building from smaller parts such as a head, a body, legs,
arms, and so on. This process of building complex objects from simpler ones is called c++
composition. It is also known as object composition.
#include <iostream>
using namespace std;
class Wall {
public:
void build() {
cout << "Building a wall." << endl;
}
};
class Door {
public:
void install() {
cout << "Installing a door." << endl;
}
};
class Window {
public:
void install() {
cout << "Installing a window." << endl;
}
};
class Roof {
public:
void build() {
cout << "Building a roof." << endl;
}
};

Page 26
UNIT-3

class House {
private:
Wall w1;
Door d1;
Window win1;
Roof roof;
public:
void build()
{
w1.build();
d1.install();
win1.install();
roof.build();
cout << "House built";
}
};
int main() {
House myHouse;
myHouse.build();
return 0;
}
Composition in Java:
class Engine {
public void start() {
System.out.println("Starting engine...");
}
}
public class Car {
private Engine engine;
public Car() {
this.engine = new Engine();
}
public void start() {
engine.start();
System.out.println("Car started.");
}
public static void main(String[] args) {
Car car = new Car();

Page 27
UNIT-3

car.start();
}
}
10. Packages:
A Package is a directory that contains classes and interfaces.

Advantages of Packages:
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Types of packages:
There are two types of packages.
1. Built-in packages
2. User-defined packages

1. Built-in packages
 java.lang: lang stands for language. This package got primary classes and interfaces
essential for developing a basic Java program.
 Java.util: util stands for utility. This package contains useful classes and interfaces
like Stack, LinkedList, Hashtable, Vector, Arrays, etc. These classes are called
collections. There are also classes for handling date and time operations.
 java.io: io stands for input and output. This package contains streams. A stream
represents flow of data from one place to another place.
 java.awt: awt stands for abstract window toolkit. This package helps to develop
GUI (Graphics User Interface) where programs with colorful screens, paintings and
images etc., can be developed.
 javax.swing: This package helps to develop GUI like java.awt. The 'x' in javax
represents that it is an extended package which means it is a package developed from
another package by adding new features to it. In fact, javax.swing is an extended
package of java.awt.

Page 28
UNIT-3

 java.net: net stands for network. Client-Server programming can be done by using
this package.
 java.applet: Applets are programs which come from a server into a client and get
executed on the client machine on a network. Applet class of this package is useful
to create and use applets.
 java.text: This package .has two important Classes, DateFormat to format dates and
times, and NumberFormat which is useful to format numeric values.
 java.sql: sql stands for structured query language. This package helps to connect to
databases like Oracle or Sybase, retrieve the data from them and use it in a Java
program.

2. User-defined packages
Just like the Built-in packages shown earlier, the users of the Java language can
also create their own packages. They are called user-defined packages. User-defined
packages can also be imported into other classes and used exactly in the same way as the
Built-in packages. To create a package the keyword “package” is used as:
package packname;
package packname.subpackname;
 Write a program to create package with name pack and create class Addition.
Example:
package pack;
public class Addition
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The sum is "+c);
}
}
 To compile the program by using following command,
javac -d . Addition.java
 The -d option tells the Java compiler to create a separate sub directory and place the
class file there. The dot (.) after -d indicates that the package should be created in the
current directory.
 From the above statement our package with “Addition.class” is ready. The next step is
we have use the add() method in the program. For this purpose, we have to create
another class and import that package.
 Write a java program to how to use Addition class of a package pack.
Example:

Page 29
UNIT-3

import pack.Addition;
class DemoPack
{
public static void main(String[] args)
{
Addition a1=new Addition(); a1.add(15,27);
}
}
Output: The Sum is 42

Example: Write a program to create package with name pack and create class Calculator
and use them another class.
Example:
package pack;
public class Calculator
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The Sum is "+c);
}
public void sub(int a,int b)
{
int c=a-b;
System.out.println("The Subtraction is "+c);
}
public void mul(int a,int b)
{
int c=a*b;
System.out.println("The Multiplication is "+c);
}
public void div(int a,int b)
{
int c=a/b;
System.out.println("The Division is "+c);
}
}
Output: javac –d . Calculator.java
Main Class:
import pack.Calculator;
class DemoPack2
{
public static void main(String[] args)
{
Calculator c=new Calculator(); c.add(15,27);
c.sub(35,5);
c.mul(15,22);
c.div(45,5);
}
}
Output: javac
DemoPack2.java java
DemoPack2

Page 30
UNIT-3
The Sum is 42
The Subtraction is 30
The Multiplication is 330
The Division is 9

11. Setting CLASSPATH:


If the above package “pack” is not available in the current directory, then what
happens? Suppose our program is running in D:\ and the package available in C:\sub. In
this case, the compiler should be given information regarding the package location by
mentioning the directory of the package in class path.

The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import. CLASSPATH is generally set to a directory or a JAR (Java
Archive) file.

Example:

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides ex: “c:\classes”.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple

12. Import Keyword: To import the java package into a class, we need to use the java
import keyword which is used to access the package and its classes into the java program. Use
import to access built-in and user-defined packages into your java source file to refer to a class
in another package by directly using its name.
13. StringTokenizer in Java

Page 31
UNIT-3

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way
to break a String. It is a legacy class of Java.

Syntax:

StringTokenizer(String str): It creates StringTokenizer with specified string.

Methods
 boolean hasMoreTokens(): It checks if there is more tokens available.
 String nextToken(): It returns the next token from the StringTokenizer object.
 String nextToken(String delim): It returns the next token based on the delimiter.
 boolean hasMoreElements(): It is the same as hasMoreTokens() method.
 Object nextElement(): It is the same as nextToken() but its return type is Object.
 int countTokens(): It returns the total number of tokens.

Example:
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("this is oops class"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:
this
is
oops
class

14. Math class in java


public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
double a = 30;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("Logarithm of x is: " + Math.log(x));

Page 32
UNIT-3

System.out.println("exp of a is: " +Math.exp(x));


System.out.println("Sine value of a is: " +Math.sin(a));
System.out.println("Cosine value of a is: " +Math.cos(a));
System.out.println("Tangent value of a is: " +Math.tan(a));
}
}
Output:
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
exp of a is: 1.446257064291475E12
Sine value of a is: -0.9880316240928618
Cosine value of a is: 0.15425144988758405
Tangent value of a is: -6.405331196646276
15. Util class in java
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");

String userName = myObj.nextLine();


System.out.println("Username is: " + userName);
}
}

Page 33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy