0% found this document useful (0 votes)
15 views21 pages

Oops 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views21 pages

Oops 2

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

UNIT II FEATURES OF OBJECT ORIENTED PROGRAMMING

Class - Objects - Encapsulation - Constructors - this keyword – Inheritance: Single, Multilevel, hierarchy –
Abstraction: Abstract class – Interface: Simple and Nested – Multiple Inheritance - Packages.

2.1 FEATURES OF OBJECT-ORIENTED PROGRAMMING


Object-Oriented Programming (OOP) is a programming language model organized around objects
rather than actions and data. An object-oriented program can be characterized as data controlling access to code.
Features of OOPS

1. Object
2. Class
3. Encapsulation
4. Inheritance
5. Polymorphism
6. Abstraction
1.OBJECT:
 Object is the physical as well as logical entity whereas class is the only logical entity.
 Object is an instance of class, object has state and behaviors.
 It is a bundle of data and its behaviour(often known as methods).
 It is a basic unit of Object Oriented Programming and represents the real life entities.
An Object in java has three characteristics:
 State
 Behavior
 Identity
1.State : It is represented by attributes of an object. It also reflects the properties of an object.
2.Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects.
3.Identity : It gives a unique name to an object and enables one object to interact with other objects.

Objects have two characteristics: They have states and behaviors.


Examples of states and behaviors
Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door
class House {
String address;
String color;
double are;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...
}
2.CLASS
A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Body: The class body surrounded by braces, { }.
Syntax to declare a Class
class Class_Name
{
data member;
method;
}
Difference between Class and Object in Java
Class Object
1 Class is a container which collection of
object is an instance of class
variables and methods.
2 No memory is allocated at the time of Sufficient memory space will be allocated for all
declaration the variables of class at the time of declaration.
3 One class definition should exist only once
For one class multiple objects can be created.
in the program.

Example
class Employee
{
int eid; // data member (or instance variable)
String ename; // data member (or instance variable)
eid=101;
ename="Hitesh";
public static void main(String args[])
{
Employee e=new Employee(); // Creating an object of class Employee
System.out.println("Employee ID: "+e.eid);
System.out.println("Name: "+e.ename);
}
}
Output
Employee ID: 101
Name: Hitesh

3.ENCAPSULATION

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation.
Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation
can be achieve using class keyword, state represents declaration of variables and behavior represents method.
Advantage of Encapsulation : to secure the data from other methods, when we make a data private then these data
only use within the class, but these data not accessible outside the class.
Benefits of encapsulation
 Provides abstraction between an object and its clients.
 Protects an object from unwanted access by clients.
 Example: A bank application forbids (restrict) a client to change an Account's balance.

4.INHERITANCE
 Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from the
parent class.
 When one object acquires all the properties and behaviors of another object, it is known as
inheritance. It provides code reusability and establishes relationships between different classes.
 A class which inherits the properties is known as Child Class (sub-class or derived class) whereas a
class whose properties are inherited is known as Parent class (super-class or base class).
 Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple and hybrid
inheritance is supported through interface only.
5.POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

Polymorphism is classified into two ways:


Method Overloading (Compile time Polymorphism)
Method Overloading is a feature that allows a class to have two or more methods having the same name but the
arguments passed to the methods are different. Compile time polymorphism refers to a process in which a call to
an overloaded method is resolved at compile time rather than at run time.
Method Overriding (Run time Polymorphism)
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 subclass provides the specific implementation of the method that has been provided by one
of its parent class, it is known as method overriding.
6.ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
For example: phone call, we don't know the internal processing.In java, we use abstract class and interface to
achieve abstraction.
2.2 CONSTRUCTORS
 A constructor is a block of codes similar to the method. It is called when an instance of the object is created,
and memory is allocated for the object.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using new() keyword, at least one constructor is called. It calls a default
constructor.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary
to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have
any.
1.Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>()
{
}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
creation.
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created

2.Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have
any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Output:

111 Karan
222 Aryan

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:

111 Karan 0
222 Aryan 25

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from one object to another like
copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.

//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Output:

111 Karan
111 Karan
Object Cloning :
The object cloning is a way to create exact copy of an object. The clone() method of Object class is used
to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to
create.
2.3 THIS KEYWORD
Uses of This keyword
 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.

1)The this keyword can be used to refer class Student


current class instance variable. If there is { int rollno;
ambiguity between the instance String name;
variables and parameters, this keyword int instcode;
resolves the problem of ambiguity.
Student(int code,int rollno,String name)
2)You may invoke the method of the {
current class by using the this keyword. this(code);
If you don't use the this keyword, this.rollno=rollno;
compiler automatically adds this this.name=name;
keyword while invoking the method this.display();
}
3) The this() constructor call can be used
to invoke the current class constructor. It Student(){}
is used for constructor chaining;
Student(int code)
4)The this keyword can also be passed {instcode=code;}
as an argument in the method. It is
mainly used in the event handling void display()
{System.out.println(instcode+” “+rollno+" "+name);}
5)We can pass the this keyword in the
constructor also. It is useful if we have Student thisret()
to use one object in multiple classes {return this;}
}
6)We can return this keyword as an
statement from the method. In such case, class TestThis
return type of the method must be the {
class type. public static void main(String args[])
{
Student s1=new Student(9213,111,"ankit");
Student s2=new Student();
s2=s1.thisret();
s2.display();
}
}
Output: 9213 111 ankit
9213 111 ankit

SUPER KEYWORD

Usage of java super Keyword

1) super.<variable_name> refers to the variable of variable of parent class.


2) super() invokes the constructor of immediate parent class.
3) super.<method_name> refers to the method of parent class.
1) super.<variable_name> to invoke Parent class variable
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1 {
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
White
Black
2) super() to invoke constructor of parent class
 When we create the object of sub class, first the constructor of parent class gets invoked and then
the constructor of child class. It happens because compiler itself adds super()[it invokes parent
class constructor] to the constructor of child class.
 super() must be the first statement in constructor otherwise we will get the compilation error
message: “Constructor call must be the first statement in a constructor”.
class Parentclass
{
Parentclass(){
System.out.println("Constructor of Superclass");
}
}
class Subclass extends Parentclass
{

Subclass(){
super();//invokes parent class constructor
System.out.println("Constructor of Subclass");
}
void display(){
System.out.println("Hello");
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.display();
}
}

Output
Constructor of Superclass
Constructor of Superclass
Hello
3) super.<method_name> to invoke parent class method

class Parentclass {
//super class method
void display(){
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass {
//Overriding method
void display(){
System.out.println("Child class method");
}
void printMsg(){
//This would call sub class method
display();
//This would call Parent class method
super.display();
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printMsg(); }
}
Output:
Child class method
Parent class method
Final Keyword In Java – Final variable, Method and Class
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) final variable
2) final method
3) final class
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}

// Output:Compile Time Error


2) Java final method
If you make any method as final, you cannot override it.
Example of final method
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();
honda.run();
}
}
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
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 Honda();
honda.run();
}
}
Output: Compile Time Error

2.4 INHERITANCE
⚫ Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
⚫ 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 parent class, and
you can add new methods and fields also.
⚫ Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
⚫ For Method Overriding (so runtime polymorphism can be achieved).
⚫ For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
1.Single Inheritance

Here A is a parent classof B and B would be a child class of A.


Example:
class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Output:
Base class method
Child class method
2.Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class.

Example:

class X {
public void methodX()
{
System.out.println("Class X method");
}
}
class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
class Z extends Y {
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Output:
Class X method
class Y method
class Z method
3.Hierarchical Inheritance
⚫ In such kind of inheritance one class is inherited by many sub classes. In below example class
B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}

}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class MyClass
{

public static void main(String args[])


{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}

The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A

2.5 ABSTRACT CLASSES


 A class that is declared using “abstract” keyword is known as abstract class.
 It may or may not include abstract methods which means in abstract class you can have
concrete methods (methods with body) as well along with abstract methods ( without an
implementation, without braces, and followed by a semicolon)
 An abstract class can not be instantiated (you are not allowed to create object of Abstract class).
Remember two rules:
1) If the class is having few abstract methods and few concrete methods: declare it as abstract class.
2) If the class is having only abstract methods: declare it as interface.(full abstraction )
ABSTRACT CLASS DECLARATION
• Abstract class declaration
Specifying abstract keyword before the class during declaration, makes it abstract.
abstract class AbstractDemo{
// Concrete method: body and braces
public void myMethod(){
System.out.println(“concrete method”);
}
// Abstract method
abstract public void anotherMethod();
}

ABSTRACT METHOD
syntax:
public abstract void display();
• Points to remember about abstract method:
1) Abstract method has no body.
2) Always end the declaration with a semicolon(;).
3) It must be overridden. An abstract class must be extended and in a same way abstract method
must be overridden.
4) Abstract method must be in a abstract class.
• Note: The class which is extending abstract class must override (or implement) all the abstract
methods.
Example:
abstract class Demo1{
public void disp1(){
System.out.println("Concrete method of abstract class");
}
abstract public void disp2();
}
class Demo2 extends Demo1{
/* I have given the body to abstract method of Demo1 class It is must if you don't declare
abstract method of super class compiler would throw an error*/
public void disp2() {
System.out.println("I'm overriding abstract method");
}
public static void main(String args[]){
Demo2 obj = new Demo2();
obj.disp2();
}
}
• Output: I'm overriding abstract method

DIFFERENCE BETWEEN ABSTRACT CLASSES AND INTERFACES

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final
and non-static variables. variables.

4) Abstract class can provide the implementation Interface can't provide the
of interface. implementation of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) Example: Example:
public abstract class Shape{ public interface Drawable{
Void display(){} public abstract void draw();
public abstract void draw(); }
}
2.6 INTERFACE
Interface is a pure abstract class. They are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body.
Interface is used to achieve complete abstraction in Java. When you create an interface it
defines what a class can do without saying anything about how the class will do it.
Why use Java interface?

It is used to achieve abstraction.


By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
2.6.1. SIMPLE INTERFACE:
Syntax :
Interfaces are declared by specifying a keyword “interface”
E.g.:
interface MyInterface {
/* All the methods are public abstract by default * Note down that these methods are not having
body */
Int a=10;
public void method1();
public void method2();
}
Rules for using Interface
 Methods inside Interface must not be static, final, native or strictfp.
 All variables declared inside interface are implicitly public static final variables (constants).
 All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't
use public or abstract keyword.
 Interface can extend one or more other interface.
 Interface cannot implement a class.
 Interface can be nested inside another interface.
 Java programming language does not support multiple inheritance, using interfaces we can
achieve this as a class can implement more than one interfaces,
1. Class->Interface “Implements”
2. Interface->Interface “extends”
3. Class->class “extends”

Example for Interface:


interface MyInterface {
public void method1();
public void method2();
}
class XYZ implements MyInterface {
public void method1() {
System.out.println("implementation of method1");
}
public void method2() {
System.out.println("implementation of method2");
}
public static void main(String arg[]) {
MyInterface obj = new XYZ();
obj. method1();
}
}
Output: implementation of method1
Example for class implements more than one interface:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable
{
public void print(){
System.out.println("Hello");

}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello Welcome
Interface->Interface
public interface Inf1
{
public void method1();
}
public interface Inf2 extends Inf1
{
public void method2();
}
public class Demo implements Inf2
{
public void method1()
{
//Implementation of method1
}
public void method2()
{
//Implementation of method2}
}
}

2.6.2 NESTED INTERFACE


An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are
used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer
interface or class. It can't be accessed directly.
Points to remember for nested interfaces
 There are given some points that should be remembered by the java programmer.
 The nested interface must be public if it is declared inside the interface, but it can have any access modifier
if declared within the class.
 Nested interfaces are declared static
Syntax of nested interface which is declared within the interface
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example (nested interface which is declared within the interface):
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[]){
Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}

Output:
hello nested interface
2.6.3 MULTIPLE INHERITANCE
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class
because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because
its implementation is provided by the implementation class. For example:

interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable


{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

Output:
Hello

2.7 Packages
PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps organize your
classes into a folder structure and make it easy to locate and use them.
Types of packages
1) Built-in packages
2) User defined packages
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly used
built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations).
This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ;
for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus
etc).
6) java.net: Contain classes for supporting networking operations.
Uses:
 The package makes the search easier for the classes and interfaces.
 It provides a fully qualified name that avoids naming conflicts.
 It also controls access.
 It organizes classes in a folder structure.
 It improves code reusability.
 Programmer can group classes and interfaces into a related package.

User-defined packages
these are the packages that are defined by the user.
How to Create a package?
Creating a package is a simple task as follows
 Choose the name of the package
 Include the package command as the first line of code in your Java Source File.
 The Source file contains the classes, interfaces, etc you want to include in the package
 Compile to create the Java packages

First we create a directory myPackage (name should be same as the name of the package). Then
create the MyClass inside the directory with the first statement being the package names.
To compile the Java programs with package statements, you have to use -d option as shown
below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
Example of Creating the package:

// Name of the package must be same as the directory


// under which this file is saved

package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}
Importing the package

/* import 'MyClass' class from 'names' myPackage */


import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
String name = "GeeksforGeeks";

// Creating an instance of class MyClass in the package.


MyClass obj = new MyClass();
obj.getNames(name);
}
}

You might also like