0% found this document useful (0 votes)
6 views

2) Constructors and Interface

The document explains constructors in programming, highlighting their role in initializing objects and detailing two types: default constructors and parameterized constructors. It also covers interfaces, which facilitate multiple inheritance by allowing classes to implement abstract methods defined in interfaces. An example is provided to illustrate how a class can implement multiple interfaces and their methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

2) Constructors and Interface

The document explains constructors in programming, highlighting their role in initializing objects and detailing two types: default constructors and parameterized constructors. It also covers interfaces, which facilitate multiple inheritance by allowing classes to implement abstract methods defined in interfaces. An example is provided to illustrate how a class can implement multiple interfaces and their methods.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

CONSTRUCTORS:

It has same name as that of class name. It is used to initialize the objects. It is invoked
implicitly.

Ex:
class student{
student(){ // constructor
System.out.println(“constructor block”);
}
public static void main(String args[]){
System.out.println(“main method block”);
}
}

There are two types of constructors:

 Default constructors – it contains no parameters. When a constructor is not defined, the


compiler adds a constructor by default.

Syntax: class_name(){}

 Parameterized constructors – user defined constructor with some parameters.

Syntax: class_name(arg1,arg2,…){}

INTERFACE:
 Interface helps to achieve Multiple Inheritance.

 Interface is a collection of abstract methods. A class inherits an interface thereby


implementing all its abstract methods.

 A class which is using interface must use “implements” keyword.

Ex:
interface Animal { // this is an interface
public void bark();
}

interface Mammals{ // this is an interface


public void eat();
}
public class Dog implements Animal,Mammals { // class which implements
interface

Animal and Mammals


public static void main(String args[]) {
Dog d = new Dog();
d.bark();
d.eat();
}

@Override
public void bark() {
// TODO Auto-generated method stub
System.out.println("This is implemented method of interface
Animal");
}

@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("This is implemented method of interface
Mammals");
}
}

Output:
This is implemented method of interface Animal
This is implemented method of interface Mammals

You might also like