Oops 2
Oops 2
Class - Objects - Encapsulation - Constructors - this keyword – Inheritance: Single, Multilevel, hierarchy –
Abstraction: Abstract class – Interface: Simple and Nested – Multiple Inheritance - Packages.
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.
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.
Output:
111 Karan
222 Aryan
111 Karan 0
222 Aryan 25
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);}
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.
SUPER KEYWORD
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).
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
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
{
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
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
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
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?
}
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}
}
}
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();
}
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:
package myPackage;