Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Lecture3 Interface

The document discusses the concepts of final classes, abstract classes, and interfaces in Java, explaining how they control inheritance and method overriding. It highlights that final classes cannot be extended, abstract classes cannot be instantiated, and interfaces provide a way to achieve multiple inheritance by allowing classes to implement multiple interfaces. Additionally, it covers the syntax for declaring and implementing these structures, along with examples of their usage.

Uploaded by

Ayushi Kapoor
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture3 Interface

The document discusses the concepts of final classes, abstract classes, and interfaces in Java, explaining how they control inheritance and method overriding. It highlights that final classes cannot be extended, abstract classes cannot be instantiated, and interfaces provide a way to achieve multiple inheritance by allowing classes to implement multiple interfaces. Additionally, it covers the syntax for declaring and implementing these structures, along with examples of their usage.

Uploaded by

Ayushi Kapoor
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

1

Parent

Inherited
capability

Child

2
 All methods and variables can be
overridden by default in subclasses.
 This can be prevented by declaring them
as final using the keyword “final” as a
modifier. For example:
◦ final int marks = 100;
◦ final void display();
 This ensures that functionality defined in
this method cannot be altered any.
Similarly, the value of a final variable
cannot be altered.

3
 We can prevent an inheritance of classes by
other classes by declaring them as final classes.
 This is achieved in Java by using the keyword
final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}
 Any attempt to inherit these classes will cause an
error.

4
 When we define a class to be “final”, it
cannot be extended. In certain situation,
we want to properties of classes to be
always extended and used. Such classes
are called Abstract Classes.
 An Abstract class is a conceptual class.
 An Abstract class cannot be instantiated –
objects cannot be created.
 Abstract classes provides a common root
for a group of classes, nicely tied
together in a package:

5
abstract class ClassName
{
...

abstract Type MethodName1();


Type Method2()
{
// method body
}
}
 When a class contains one or more abstract methods, it
should be declared as abstract class.
 The abstract methods of an abstract class must be defined
in its subclass.
 We cannot declare abstract constructors or abstract static
methods.

6
 Shape is a abstract class.

Shape

Circle Rectangle

7
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}

 Is the following statement valid?


◦ Shape s = new Shape();
 No. It is illegal because the Shape class is an
abstract class, which cannot be instantiated to
create its objects.

8
public Circle extends Shape {
protected double r;
protected static final double PI =3.1415926535;
public Circle() { r = 1.0; )
public double area() { return PI * r * r; }

}
public Rectangle extends Shape {
protected double w, h;
public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }
}
9
 A class with one or more abstract methods
is automatically abstract and it cannot be
instantiated.
 A class declared abstract, even with no
abstract methods can not be instantiated.
 A subclass of an abstract class can be
instantiated if it overrides all abstract
methods by implementing them.
 A subclass that does not implement all of
the superclass abstract methods is itself
abstract; and it cannot be instantiated.

10
 If you do not want (properties of) your class to be
extended or inherited by other classes, define it
as a final class.
◦ Java supports this is through the keyword “final”.
◦ This is applied to classes.
 You can also apply the final to only methods if
you do not want anyone to override them.
 If you want your class (properties/methods) to be
extended by all those who want to use, then
define it as an abstract class or define one or
more of its methods as abstract methods.
◦ Java supports this is through the keyword “abstract”.
◦ This is applied to methods only.
◦ Subclasses should implement abstract methods;
otherwise, they cannot be instantiated.

11
Design Abstraction and a way for
loosing realizing Multiple
Inheritance

12
 Interface is a conceptual entity similar to a
Abstract class.They contain only abstract
methods.
 They contain methods which are public &

abstract by default i.e. Methods are only declared


in interfaces but they have no defination.
 Can contain only constants (final variables) and

abstract method (no implementation) - Different


from Abstract classes.
 Use when a number of classes share a common

interface. Each class should implement the


interface.

13
 It cannot be instantiated just like the
abstract class.
 Since Java 8, we can have default and

static methods in an interface.


 Since Java 9, we can have private

methods in an interface.

14
 An interface is basically a kind of class—it
contains methods and variables, but they
have to be only abstract methods and final
fields/variables.
 Therefore, it is the responsibility of the class
that implements an interface to supply the
code for methods.
 A class can implement any number of
interfaces, but cannot extend more than one
class at a time.
 Therefore, interfaces are considered as an
informal way of realising multiple inheritance
in Java.

15
<<Interface>>
Speaker
speak()

Politician Priest Lecturer


speak() speak() speak()

16
 Variables can be declared inside of
interface declarations. They are implicitly
final and static, meaning they cannot
be changed by the implementing
class.
 They must also be initialized with a

constant value. All methods and variables


are implicitly public if the interface, itself,
is declared as public.
 Syntax (appears like abstract class):

interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}

 Example:
interface Speaker {
int i=10;
public void speak( );
}
18
 Interfaces are used like super-classes who
properties are inherited by classes. This is achieved
by creating a class that implements the given
interface as follows:
class ClassName implements InterfaceName [, InterfaceName2,
…]
{
// Body of Class
}  To implement an interface a class must create the
complete set of methods as defined by the
interface.
 A class can implement 1/more interfaces.This is
somewhat analogous to multiple inheritance in C++.

19
● Once an interface has been defined, one or
more classes can implement that interface.
● To implement an interface, include the
implements clause in a class definition, and
then create the methods defined by the
interface.
● The general form of a class that includes the
implements clause looks like this:
● access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body}
● access is either public or not used.
Note: Methods that implement interfaces
must be declared as public & type
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}

class Priest implements Speaker {


public void speak(){
System.out.println(“Religious Talks”);
}
}

class Lecturer implements Speaker {


public void speak(){
System.out.println(“Talks Object Oriented Design and Programming!”);
}
}
21
 Like classes, interfaces can also be
extended. The new sub-interface will
inherit all the members of the
superinterface in the manner similar to
classes. This is achieved by using the
keyword extends as follows:
interface InterfaceName2 extends
InterfaceName1 {
// Body of InterfaceName2
}

22
public interface AreaCalculation
{ void calc_area(); //methods have no body
void show_area();
int lenght=1;
int breadth=2;
}
public class Circle implements
AreaCalculation{
double radius=12.4;
double area;

public void calc_area() // see public


{ area = 3.14*radius*radius;
}
public void show_area(){
System.out.println(area);
}
 We can create references of the
interfaces .These interface references can
refer to any object of its implementing
classes
 When we call a method using them, the

correct version will be called depending


upon the type of the object being pointed
to.
public class square implements
AreaCalculation{
double side=12.4;
double area;

public void calc_area() // see public


{ area =side*side;
}
public void show_area(){
System.out.println(“area of square”, +area);
}}
class Test{
public static void main(String args[]){
AreaCalculation a =new Circle();
a.calc_area(); //refer to circle’s version

Square s = new Square();


a=s;
a.calc_area(); //refer to circle’s version
 If a class does not fully implement an
interface it must be declared as abstract
 Eg.

abstract class Rectangle implements


AreaCalculation{
void calc_area();
void show_area()
{System.out.println(“area of Rect is 40”);
}}
 One interface can inherit another by use of
the keyword extends. The syntax is the
same as for inheriting classes.
 When a class implements an interface that

inherits another interface, it must provide


implementations for all methods defined
within the interface inheritance chain.
interface A{
void meth1();
void meth2();
}

interface B extends A{ //B includes meth1 &


meth2
void meth3();}

class Myclass implements B


{public void meth1()
Sytem.out.println("This is meth1");}
public void meth2()

Sytem.out.println("This is meth2");
public void meth3()
Sytem.out.println("This is meth3");
}
 A general form of interface implementation:
class ClassName extends SuperClass implements InterfaceName [,
InterfaceName2, …]
{
// Body of Class
}
 This shows a class can extended another class
while implementing one or more interfaces. It
appears like a multiple inheritance (if we consider
interfaces as special kind of classes with certain
restrictions or special features).

31
 Consider a university where students who
participate in the national games or Olympics are
given some grace marks. Therefore, the final
marks awarded = Exam_Marks +
Sports_Grace_Marks. A class diagram
representing this scenario is as follow:

Student Sports

extends

Exam
implements
extends

Results
32
class Student
{
// student no and access methods
}
interface Sport
{
// sports grace marks (say 5 marks) and abstract methods
}
class Exam extends Student
{
// example marks (test1 and test 2 marks) and access methods
}
class Results extends Exam implements Sport
{
// implementation of abstract methods of Sport interface
// other methods to compute total marks =
test1+test2+sports_grace_marks;
// other display or final results access methods
}

33
 Interfaces, like abstract classes and methods,
provide templates of behaviour that other classes
are expected to implement.
 Separates out a design hierarchy from
implementation hierarchy. This allows software
designers to enforce/pass common/standard
syntax for programmers implementing different
classes.
 Pass method descriptions, not implementation
 Java allows for inheritance from only a single
superclass. Interfaces allow for class mixing.
 Classes implement interfaces.

34
Program to demonstrate multiple inheritance using interfaces
interface adder
{
void add();
void sub();
}
interface multiplier
{void mul();
void div();}

class Mycal implements adder,multiplier


{
int a,b;
Mycal( int x, int y)
{ a=x; b=y;}

public void add ()


{ System.out.println("Sum of no.s is:" +(a+b));
}

public void sub()


{System.out.println("Subtraction is:" +(a-b));
}
public void mul()
{System.out.println("Multiplication is:" +(a*b));
}
public void div()
35
{System.out.println("Division is:" +(a/b));
class Interface_Demo {
public static void main(String args[]){
Mycal m =new Mycal (8,7);
m.add();
m.sub();
m.div();
m.mul():

36
37
 Class is a collection of data and methods
that operate on that data
 An object is a particular instance of a class
 Object members accessed with the ‘dot’

(Class.v)
 Instance variables occur in each instance

of a class
 Class variables associated with a class
 Objects created with the new keyword

38
 Objects are not explicitly ‘freed’ or destroyed.
Java automatically reclaims unused objects.
 Java provides a default constructor if none
defined.
 A class may inherit the non-private methods
and variables of another class by subclassing,
declaring that class in its extends clause.
 java.lang.Object is the default superclass for
a class. It is the root of the Java hierarchy.

39
 Data and methods may be hidden or
encapsulated within a class by specifying
the private or protected visibility modifiers.
 An abstract method has no method body.
An abstract class contains abstract
methods.
 An interface is a collection of abstract
methods and constants. A class implements
an interface by declaring it in its
implements clause, and providing a method
body for each abstract method.

40
 Method overloading is the practice of
defining multiple methods which have the
same name, but different argument lists
 Method overriding occurs when a class
redefines a method inherited from its
superclass
 static, private, and final methods cannot
be overridden
 From a subclass, you can explicitly invoke
an overridden method of the superclass
with the super keyword.

41

You might also like