[go: up one dir, main page]

0% found this document useful (0 votes)
14 views35 pages

6 Const Inheri Interf Abst (Unit 1)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 35

Web Technology

Constructors, Inheritance,

Interface and Abstract class


Contents
 Constructors

 Inheritance

 Interface and Abstract class


Constructors
Constructor is a special type of method that is used to initialize the object.
It is invoked at the time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as constructor.

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1.Default constructor (no-arg constructor) 2. Parameterized


constructor
Default Constructor
A constructor that have no parameter is known as default constructor.
It will be invoked at the time of object creation.

Syntax:
<class_name>(){}

Example:
class Book{
Book(){
System.out.println("Book is published");}
public static void main(String args[])
{
Book b=new Book(); Output: Book is published
}}
Another Example:

class AddDemo1
{
AddDemo1()
{
int a=10;
int b=5;
int c;
c=a+b;
System.out.println("*****Default Constructor*****");
System.out.println("Total of 10 + 5 = "+c);
}

public static void main(String args[])


{
AddDemo1 obj=new AddDemo1();
}
}
Example of parameterized constructor

Constructor of Student class that have two parameters.


We can have any number of parameters in the constructor.
class Student{
int id; String name;

Student(int i,String n){


id = i; name = n;
}
void display(){
System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Avi");
s1.display();
s2.display(); } }
Constructor Overloading
A technique in which a class can have any number of constructors that differ in parameter lists.
Compiler differentiates these constructors by the number of parameters in the list & their type.
class Student{
int id; String name; int age;
Example: Student(int i,String n){
id = i;
name = n;
} Output:
Student(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[]){


Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Abhi",25);
s1.display(); s2.display(); }}
Constructor Chaining
Process of calling one constructor from another constructor in the same class.
Since constructor can only be called from another constructor, constructor chaining is
used for this purpose.

To call constructor from another constructor this keyword is used.


this keyword is used to refer current object. class Test {
Test() {
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
public static void main(String arg[]) {
Test object = new Test();
} }
Constructor chaining is used when we want to perform multiple tasks by creating a
single object of the class.
Here we have created three constructors and calling them using by using this keyword.

class abc {
public abc() {
this(5);
System.out.println("Default Constructor");
}
public abc(int x)
{
this(5, 6);
System.out.println("Constructor with one Parameter");
System.out.println("Value of x ==> "+x);
}
public abc(int x, int y)
{
System.out.println("Constructor with two Parameter");
System.out.println("Value of x and y ==> "+x+" "+y);
}
}
class ChainingDemo1
{
public static void main(String as[])
{
abcobj = new abc(); }}
Copy Constructor

There is no copy constructor in java.


But, we can copy the values of one object to another like copy constructor in C++.

Ways to copy the values of one object into another are:

• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
Example:
To copy the values of one object into another using constructor:
class Student{
int id; String name;
Student(int i, String n){
id = i;
name = n;
}

Student(Student s){
id = s.id; Output:
name =s.name;
}
void display(){
System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Kiran");
Student s2 = new Student(s1);
s1.display();
s2.display();
}}
Difference between constructor and method

Constructor Method

used to initialize the state of an object. used to expose behaviour of an object.

must not have return type. must have return type.

invoked implicitly. invoked explicitly.

compiler provides a default constructor if not specified. not provided by compiler in any case.

name must be same as the class name. may or may not be same as class name.
Constructor Overloading
A technique having class with any number of constructors that differ in parameter lists.
Compiler differentiates these constructors by the number of parameters and their type.
Example: class Student{
int id; String name; int age;
Student(int i,String n){ Output:
id = i; name = n;
} 111 Kiran 0
Student(int i,String n,int a){
id = i; 222 Abhi 25
name = n;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Abhi",25);
s1.display();
s2.display(); } }
INHERITANCE IN JAVA
It is a mechanism in which one object acquires all the properties and behaviors of a parent object.
•It is an important part of OOPs
•Idea behind inheritance: We can create new classes that are built upon existing classes.
•When existing class gets inherited, we can reuse methods and fields of the parent class.
• Moreover, we can add new methods and fields in our current class also.
•Represents the IS-A relationship which is also known as a parent-child relationship.

Usefulness of Inheritance:

1. For Method Overriding (so runtime polymorphism can be achieved).


2. For Code Reusability.
Terms used in Inheritance

•Class: group of objects which have common properties. A blueprint from which objects are created.
•Sub Class/Child Class: class which inherits other class. Also called a derived class or extended class.
•Super Class/Parent Class: class from where a subclass inherits the features. Also called a base class
•Reusability: Able to use the same fields and methods already defined in previous class by a new class

Syntax of Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword used to make a class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
class which is inherited is called a superclass, and the new class is called subclass.
Example:
In this figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.

class Employee{
float salary=80000;
}
class Programmer extends Employee{ Output:
int bonus=25000;
public static void main(String args[]){ Programmer salary is:80000.0
Programmer p=new Programmer(); Bonus of programmer is:25000
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
} }

In this example:
Programmer object can access its own field as well as of Employee class i.e. code
reusability.
Types of Inheritance
1) Single Inheritance: relationship where a class extends the another class.

2) Multilevel inheritance: relationship where a class extends the child class.


For example class C extends class B and class B extends class A.

3) Hierarchical inheritance: more than one classes extends


the same class. For example, classes B & C extends the
same class A.

• In java, multiple & hybrid inheritance is supported through interface only.


Ex. of Single Inheritance
class A{
String bookname=“WEB TECH”;
void show() {
System.out.println(" Book Name = "+ bookname);
}
}
public class B extends A{
int price=250;
void display()
{
System.out.println(" Book Price= "+ price);
}
public static void main(String[] args) {
B b = new B();
b.show();
b.display();
}
}
Ex. of Multilevel Inheritance
class A{
String bookname=“Java”;
void show() {
System.out.println(" Book Name = "+ bookname);
} }
class B extends A{
int price=700;
void display()
{
System.out.println(" Book Price= "+ price);
}
public class C extends B{
public static void main(String[] args) {
C c = new C();
c.show();
c.display();
} }
Ex. of Hierarchical Inheritance
class A{
String bookname="Oracle";
void show() {
System.out.println(" Book Name = "+ bookname);
} }

class B extends A{
int edition=2;
void display() {
System.out.println(" Book Edition= "+ edition);
}}

class C extends A{
String publisher="TMH";
void print() {
System.out.println(" Book Publisher="+publisher);}}
class D{
public static void main(String[] args) {
B b=new B(); b.show(); b.display() ;
C c = new C(); c. show(); c.print();
} }
INTERFACE
An interface is a blueprint of a class. It has static constants and abstract methods.
•It is used to achieve abstraction and multiple inheritance in Java.
•There can be only abstract methods in the java interface not method body.
•Java Interface also represents IS-A relationship.
•It cannot be instantiated just like abstract class.
reasons to use interface:
• to achieve abstraction.
• to support the functionality of multiple inheritance.
Declare an interface: using the interface keyword.

It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default.
- A class that implements an interface must implement all methods declared in interface.
• Java compiler adds public & abstract keywords before
Syntax: the interface method.
• Also adds public, static and final keywords before data
interface <interface_name>{ members.
• Thus, Interface fields are public, static and final by
// declare constant fields default, and the methods are public and abstract.
// declare methods that abstract by default.
}

Relationship b/w classes & interfaces


A class extends another class, an interface extends another interface, but a class
implements an interface.
Interface Example: Bank
Example: implementation of Bank interface:
File: MyInterface.java
interface Bank{
float printROI(); }

class SBI implements Bank{


public float printROI(){
return 9.10f;} }

class BOB implements Bank{


public float printROI(){
return 8.15f;} }

class MyInterface{
public static void main(String args[]){
Bank ob1 = new SBI();
Bank ob2 = new BOB();
System.out.println("Hello");
System.out.println(ob1.printROI());
System.out.println(ob2.printROI()); } }
Multiple inheritance in Java by Interface:
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.

Example:

interface Printable{
void print(); }

interface Showable{
void print(); }

class MyInterface implements Printable, Showable{


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

Printable and Showable interface have same methods but its implementation is provided
by class MyInterface1, so there is no ambiguity.
Interface Inheritance
A class implements an interface, but one interface extends another interface.

interface Printable{
void print(); }
interface Showable extends Printable{
void show(); }
Output:
Hello Welcome
class MyInterface implements Showable{
public void print()
{ System.out.println("Hello"); }
public void show()
{ System.out.println("Welcome"); }

public static void main(String args[]){


MyInterface obj = new MyInterface();
obj.print();
obj.show();
}
}
Abstract Class
• A class which is declared using abstract keyword known as abstract class.
• It can have abstract and non-abstract methods.
• Cannot create object of abstract class(Can’ be instantiated) but they can be subclassed.
• Used to achieve abstraction but it does not provide 100% abstraction because it can
have concrete methods.

Syntax:

abstract class class_name { }


Abstract method

Method that are declared without any body within an abstract class.
The method body will be defined by its subclass.
Abstract method can never be final and static.
Any class that extends an abstract class must implement all the abstract
methods.
Syntax: abstract return_type function_name ();
About Abstract Class and Method

1. Abstract classes are not Interfaces.


2.An abstract class may or may not have an abstract method.
3.But if any class has even a single abstract method, then it must be declared abstract.
4.Abstract classes can have Constructors, Member variables and Normal methods.
5.Abstract classes are never instantiated.
6.When Abstract class is extended with abstract method, we must define the abstract
method in the child class, or make the child class abstract.
Example of Abstract class
abstract class A {
abstract void display();
}
class B extends A
{
void display()
{
System.out.println("From parents
Displaying...");
}
void show()
{
System.out.println("In child...");
}
public static void main(String[] args)
{
B b = new B();
b.show();
b.display();
}
}
Abstract class with non-abstract method
Abstract classes can also have non abstract methods along with abstract methods.
But, while extending the class, provide definition for the abstract method.

abstract class A {
abstract void ROI();
public void show() {
System.out.println("this is non-abstract method");
}
}

class B extends A
{
void ROI() {
System.out.println("Calling parent... Rate of Interest!!!!");
}
public static void main(String[] args) {
B b = new B();
b.ROI();
b.show();
} }
Abstraction using Abstract class
Abstraction: An important feature of OOPS.
It means hiding complexity from users and show them only functionality.
Abstract class is used to provide abstraction although it does not provide 100% abstraction because it can also
have concrete method.
abstract class student
{
public abstract void fees();
}
public class accounts extends student {
public void fees() {
System.out.println("Fees is :50000");
// student fees implementation
}
public static void main(String[] args) {
student st= new accounts();
st.fees();
} }
Here by casting instance of accounts type to student reference, we are hiding the complexity
of accounts type under student. Now the student reference can be used to provide the
implementation but it will hide the actual implementation process.
When to use Abstract Methods & Abstract Class?
Abstract methods:
where two or more subclasses are expected to do a similar thing in different ways
through different implementations. These subclasses extend the same Abstract
class and provide different implementations for the abstract methods.

Abstract classes:
used to define generic types of behaviors at the top of an OOPg class hierarchy, and
use its subclasses to provide implementation details of the abstract class.
Abstract class Interface
Abstract class is a class which contain one or Interface is a Java Object containing method
more abstract methods, which has to be declaration but no implementation. The classes
implemented by its sub classes. which implement the Interfaces must provide
the method definition for all the methods.

Abstract class is a Class prefix with an abstract Interface is a pure abstract class which starts
keyword followed by Class definition. with interface keyword.

Abstract class can also contain concrete Whereas, Interface contains all abstract
methods. methods and final variable declarations.
Abstract classes are useful in a situation that Interfaces are useful in a situation that all
Some general methods should be implemented properties should be implemented.
and specialization behavior should be
implemented by child classes.
Thank
You

You might also like