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

INFO410-1

The document discusses key concepts in Java programming, including multiple classes, encapsulation, inheritance, and polymorphism. It provides code examples to illustrate encapsulation through accessor and mutator methods, inheritance with subclasses, and polymorphism through method overloading. Additionally, it outlines advantages of encapsulation and rules for inheritance, along with practice questions for further understanding.

Uploaded by

ndunachantelle77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views76 pages

INFO410-1

The document discusses key concepts in Java programming, including multiple classes, encapsulation, inheritance, and polymorphism. It provides code examples to illustrate encapsulation through accessor and mutator methods, inheritance with subclasses, and polymorphism through method overloading. Additionally, it outlines advantages of encapsulation and rules for inheritance, along with practice questions for further understanding.

Uploaded by

ndunachantelle77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 76

Multiple Classes

• A package is a collection of classes

• We can create a project with several methods


and variable but there should be a controlling
class that enables us to create instances for
other classes

1
class Laptop {

Laptop() {

System.out.println("Constructor of Laptop class.");

void laptop_method() {

System.out.println("99% Battery available.");

} }

public class Computer {

Computer() {

System.out.println("Constructor of Computer class.");

void computer_method() {

System.out.println("Power gone! Shut down your PC soon...");

public static void main(String[] args) {

Computer my = new Computer();

Laptop your = new Laptop();

my.computer_method();

your.laptop_method();

2
public class RunEncap{

public static void main(String args[]){

EncapTest encap = new EncapTest();

encap.setName(“John");

encap.setAge(31);

encap.setIdNum(“582144");

System.out.print("Name : " + encap.getName() + "


Age : " + encap.getAge());

} 3
Encapsulation

• Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation the variables of a
class will be hidden from other classes, and can be accessed only through the methods
of their current class, therefore it is also known as data hiding.
• The principle of encapsulation dictates that an object should have total control of its
data. That is, another object should not change the data without the owner knowing.
• This is achieved in java by declaring instance variables as private.
• It is the bringing together of data and operations - Encapsulation.
• To achieve encapsulation in Java
• Declare the variables of a class as private.

• Provide public setter and getter methods to modify and view the variables values.

• A method that changes the value of some instance variable is called a mutator
method.

4
Encapsulation

Advantage of Encapsulation in java


•By providing only setter or getter method, you can make the class
fields read-only or write-only.
•It provides you the control over the data. Suppose you want to set
the value of id i.e. greater than 100 only, you can write the logic inside
the setter method.
•The users of a class do not know how the class stores its data. A class
can change the data type of a field and users of the class do not need
to change any of their code.

5
Accessor and mutator methods

• Accessor methods are public methods that allow the programmer to obtain the
value of an object's instance variables
• The data can be accessed but not changed

• The name of an accessor method typically starts with the word get

• Mutator methods allow the programmer to change the value of an object's


instance variables in a controlled manner
• Incoming data is typically tested and/or filtered

• The name of a mutator method typically starts with the word set

• Sometimes an object cannot help but provide methods that changes the
values of its variables. Such methods are called Mutator methods

6
Example Code
public class Student{
private String name;

public String getName(){


return name;
}
public void setName(String name){
this.name=name
}
public static void main(String[] args){
Student s=new Student();
s.setname(“Furusa Samuel");
System.out.println(s.getName());
}

}
7
public class EncapTest{ }

private String name; public void setAge( int newAge){

age = newAge;
private String idNum;
}
private int age;
public void setName(String
public int getAge(){
newName){
return age; } name = newName; }
public String getName(){
public void setIdNum( String
return name; } newId){
public String getIdNum(){ idNum = newId;

return idNum; }

8
public class RunEncap{

public static void main(String args[]){

EncapTest encap = new EncapTest();

encap.setName(“Simba");

encap.setAge(31);

encap.setIdNum(“582144");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());

9
Example 2
class Student{

String id;

private double totalScore;

private int numOfQuizes;

public Student(String _id){

id = _id;

totalScore = 0; }

public double getTotalScore(){

return totalScore;

public void addQuiz(double score){

totalScore += score;

numOfQuizes++;

public double getAvarage(){

return totalScore / numOfQuizes; }

public String toString(){

return "Student id : " + id + "\tAvarage Score : " + getAvarage();

}
10
}
public class Teste {

public static void main(String []args){

Student t= new Student("R0435605");

t.addQuiz(85);

//t.getTotalScore();

System.out.println(t.toString());

}
11
Inheritance
• Inheritance can be defined as the process where one class acquires
the properties (methods and fields) of another. With the use of
inheritance the information is made manageable in a hierarchical
order.
• The class which inherits the properties of another class is known as
subclass (derived class, child class) and the class whose properties
are inherited is known as superclass (base class, parent class).
• 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. 12


Types of inheritance
• There can be three types of inheritance in java: single, multilevel and hierarchical.
• In java programming, multiple and hybrid inheritance is supported through interface
only.

13
Inheritance Syntax
class Super{

.....

class Sub extends Super{

.....

The extends keyword indicates that you are making a new class
that derives from an existing class.
•In the terminology of Java, a class that is inherited is called a super
class. The new class is called a subclass.
14
Syntax with code snippets

15
Rules for Inheritance

• 1. Private members of the superclass are not inherited by the


subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also
not inherited by subclasses in other packages, as these members
are only accessible by their simple names in subclasses within the
same package as the superclass.
3. Since constructors and initializer blocks are not members of a
class, they are not inherited by a subclass.
4. A subclass can extend only one superclass
• Methods marked final cannot be inherited

16
Example
class Super_class{

int num=20;

//display method of superclass

public void display(){

System.out.println("This is the display method of superclass");

public class Sub_class extends Super_class {

int num=10;

//display method of sub class

public void display(){

System.out.println("This is the display method of subclass");

public void my_method(){

//Instantiating subclass

Sub_class sub=new Sub_class();

17
Example 2
public class A {

int x,y,z;

public void f(){

System.out.print("Java");

public class B extends A {

int d;

public class C extends B {

int f;

public class Example {

public static void main(String [] args){

A a= new A();

B b= new B();

C c= new C();

b.x= 0;

c.f();
18
}}
Question 1
1. Create a class, Person, with an instance variable, name. Write appropriate
accessor and mutator methods for the class. Also write a toString method for the
class.
2. Employee, that extends Person, and has: two additional instance variables, ID and
payRate; and an additional method, pay, that returns the payRate. Override the
toString method accordingly.
3. Faculty, that extends Employee, and has two additional variables; officeHours of
type String and teachingCourses, which is an array of Courses. Each course has
course code and course title. Write appropriate accessor, mutator and toString
methods for the class.
4. TestPersons, that has two methods: void printPerson(Person p) that prints its
argument. And a main method that creates an instance of each of the above
classes and prints it using printPerson method.

19
Inheritance and Constructors

• Since constructors cannot be inherited within the subclass there is need to have reference
super class members within the sub class
• We use the super() keyword to access such members
• If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the super class. But if you want to call a parameterised constructor of the
super class, you need to use the super keyword as shown below.
• super(values);

20
Inheritance and Constructors cont’d
class Superclass{

int age;

Superclass(int age){

this.age=age;

public void getAge(){

System.out.println("The value of the variable named age in super class is: " +age);

public class Subclass extends Superclass {

Subclass(int age){

super(age);

public static void main(String argd[]){

Subclass s= new Subclass(24);

s.getAge();

} 21
Inheritance and Constructors Example 2
class Student {
private long id;
private String name;
private double gpa;
public Student(long id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}
public Student() {
this(999999, "No name", 0.0);
}
public void changeGPA(double newGPA) {
gpa = newGPA;
}
public double getGPA() {
return gpa;
}
public void print() {
System.out.print(id+" "+name+ " "+gpa);
}
}

22
Inheritance and Constructors Example 2
class ResearchAssistant extends Student {
private int workLoad; // in hours
ResearchAssistant(long id, String name, double gpa,int workLoad){
super(id, name, gpa);
this.workLoad = workLoad;
}
ResearchAssistant() {
super();
workLoad = 0;
}
public void print() {
super.print();
System.out.print(" " + workLoad);
}
}
class TestReserchAssistant {
public static void main (String[] args) {
ResearchAssistant s1 = new
ResearchAssistant();
s1.print();
ResearchAssistant s2 = new ResearchAssistant(991234, "Al-Ghamdi Ahmed",3.45,15);
s2.changeGPA(3.75);
s2.print();
}
}

23
Practice Question 1
a) Create a class called Customer which contains personal details of such as AccNo,
Name, Address. Include a constructor which is parameterised and get methods for
each variable. Given that Bill is derived from Customer. Bill class also contains
variables fixed_charge which is static being equal to 13.00, units and rate.

b) Demonstrate how we can access the constructor you created in a within Bill
constructor

c) Bill also contains a method which calculates the bill using the formula: bill=
fixed_charge+ units*rate

d) Create your instance within the main to display the customer details and the bill due.
The program should accept user input.

24
Practice Question 2

• Write a program that demonstrates the following forms of inheritance


• Multilevel
• Hierarchical Inheritance

25
Multilevel Inheritace

class A{

int x;

class B extends A{

int y;

class C extends B{

int p;

public C() {

x=15;

y=340;

p= x+y;

void display(){

System.out.printf("The sum of the three is %d", p);

System.out.println();

} 26
Multilevel Inheritace

public class Teste {

public static void main(String [] args){

C X= new C();

X.display();

27
Example
class Person

String FirstName;

String LastName;

Person(String fName, String lName)

{ FirstName = fName;

LastName = lName;

void Display()

System.out.println("First Name : " + FirstName);

System.out.println("Last Name : " + LastName);

28
Example
class Student extends Person

int id;

String standard;

String instructor;

Student(String fName, String lName, int nId, String stnd, String instr)

super(fName,lName);

id = nId;

standard = stnd;

instructor = instr;

void Display()

{ super.Display();

System.out.println("ID : " + id);

System.out.println("Standard : " + standard);

System.out.println("Instructor : " + instructor);

}}

29
Example
class Teacher extends Person

String mainSubject;

int salary;

String type; // Primary or Secondary School teacher

Teacher(String fName, String lName, String sub, int slry, String sType)

super(fName,lName);

mainSubject = sub;

salary = slry;

type = sType;

void Display()

super.Display();

System.out.println("Main Subject : " + mainSubject);

System.out.println("Salary : " + salary);

System.out.println("Type : " + type);

}}

class InheritanceDemo

public static void main(String args[])

Person pObj = new Person("Rayan","Miller");

Student sObj = new Student("Jacob","Smith",1,"1 - B","Roma");

Teacher tObj = new Teacher("Daniel","Martin","English","6000","Primary Teacher");

System.out.println("Person :");

pObj.Display();

System.out.println("");

System.out.println("Student :");

sObj.Display();

System.out.println("");

System.out.println("Teacher :"); tObj.Display();

30
Example
class Teacher extends Person

{String mainSubject;

int salary;

String type; // Primary or Secondary School teacher

Teacher(String fName, String lName, String sub, int slry, String sType)

{ super(fName,lName);

mainSubject = sub;

salary = slry;

type = sType;

void Display()

super.Display();

System.out.println("Main Subject : " + mainSubject);

System.out.println("Salary : " + salary);

System.out.println("Type : " + type);

}}

31
Example
class InheritanceDemo

public static void main(String args[])

Person pObj = new Person("Rayan","Miller");

Student sObj = new Student("Jacob","Smith",1,"1 - B","Roma");

Teacher tObj = new Teacher("Daniel","Martin","English","6000","Primary Teacher");

System.out.println("Person :");

pObj.Display();

System.out.println("");

System.out.println("Student :");

sObj.Display();

System.out.println("");

System.out.println("Teacher :");

tObj.Display();

32
Polymorphisn
• Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
• There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method overriding.
• If you overload static method in java, it is the example of compile time polymorphism. Here, we will
focus on runtime polymorphism in java.

Runtime Polymorphism in Java


• Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.

• In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference

variable.

33
RunTime Polymorphism
• The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a
subclass can implement a parent class method based on its requirement. In object oriented terms, overriding
means to override the functionality of any existing method.
Rules for method overriding:
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original overridden method in
the super class.
• The access level cannot be more restrictive than the overridden method's access level. For example: if the super
class method is declared public then the overridding method in the sub class cannot be either private or
protected. However the access level can be less restrictive than the overridden method's access level.
• A method declared final cannot be overridden.
• A subclass within the same package as the instance's superclass can override any superclass method that is
not declared private or final.
• A subclass in a different package can only override the non-final methods declared public or protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws
exceptions or not. However the overridden method should not throw checked exceptions that are new or broader
than the ones declared by the overridden method. The overriding method can throw narrower or fewer
exceptions than the overridden method.
• Constructors cannot be overridden.

34
RunTime Polymorphism
Upcasting
•When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:

class A{ }
class B extends A{}
A a=new B();//upcasting

35
RunTime Polymorphism
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}
}
Output:running safely with 60km.

36
RunTime Polymorphism
class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
}
public class TestDog{

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object or Dog b= new Dog()

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class


}
}

37
class Animal{
public void move(){ RunTime Polymorphism
System.out.println("Animals can move");
}}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}}
This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of
bark.
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
38
Polymorphic Arrays, inheritance and Overrding

• It is possible for a parent class to reference subclass members using a Polymorphic Array.
class Shape{
protected double dim1, dim2;
public Shape(double dim1, int dim2) {
this.dim1 = dim1;
this.dim2 = dim2;
}
public double calcArea(){

return 1;
}
}
class Rectabgle extends Shape{
public Circle(double dim1, int dim2) {
super(dim1, dim2);
}
public double calcArea(){
double area;
area= 2*(dim1+ dim2);
String s= getClass().getSimpleName();
System.out.println("Areas for : " + s + "==" + area );
return area; }

39
Polymorphic Arrays, inheritance and Overrding

class Triangle extends Shape{


public Triangle(double dim1, int dim2) {
super(dim1, dim2);
}
public double calcArea(){
double area;
area= 2*(dim1+ dim2);
String s= getClass().getSimpleName();
System.out.println("Areas for : " + s + "==" + area );
return area;
}

}
public class Sim23{
public static void main(String [] args){
Shape a[]= new Shape[2];
Triangle t= new Triangle(12,15);

Circle c= new Circle(3.14, 25);


a[0] = t;
a[1] = c;

for(int i= 0; i<2; i++)


System.out.println("Area for is " + a[i].calcArea());
}
} 40
Uses of the super keyword
Two uses of super:

1) to invoke the super-class constructor

super();

2) to access super-class members

super.variable;

super.method(…);

41
Super in variables
class A {

int i = 1;

class B extends A {

int i;

B(int a, int b) {

super.i = a; i = b;

void show() {

System.out.println("i in superclass: " + super.i);

System.out.println("i in subclass: " + i);

class UseSuper {

public static void main(String args[]) {

B subOb = new B(1, 2);

subOb.show();

42
Super in Methods
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{

public void move(){


super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}

}
public class TestDog{

public static void main(String args[]){

Dog b = new Dog(); // Animal reference but Dog object


b.move();//Runs the method in Dog class

}
}
This would produce following result:
Animals can move
Dogs can walk and run

43
Super in Methods 2
class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A {
int j;
B(int a, int b, int c) {
super(a, b);
j = a+b+c;
}
void add() {
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding {
public static void main(String args[]) {

B b = new B(10, 20, 30);


b.add();
}
}
44
Method Overloading
• If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
• If we have to perform only one operation, having same name of the methods increases the readability of the
program.
• Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you
write the method such as a( int, int) for two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behaviour of the method because its name
differs. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?


• Method overloading increases the readability of the program.
• Different ways to overload the method

1. By changing number of arguments

2. By changing the data type of arguments

45
Method Overloading
Method 1

class Calculation{

void sum(int a,int b){System.out.println(a+b);}

void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){

Calculation obj=new Calculation();

obj.sum(10,10,10);

obj.sum(20,20);

Method 2

class Calculation2{

void sum(int a,int b){System.out.println(a+b);}

void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){

Calculation2 obj=new Calculation2();

obj.sum(10.5,10.5);

obj.sum(20,20);

}
46
}
Method Overloading
In java, method overloading is not possible by changing the return type of the method because there may occur
ambiguity. Let's see how ambiguity may occur:

because there was problem:

class Calculation3{

int sum(int a,int b){System.out.println(a+b);}

double sum(int a,int b){System.out.println(a+b);}

public static void main(String args[]){

Calculation3 obj=new Calculation3();

int result=obj.sum(20,20); //Compile Time Error

47
Method Overloading vs Overriding

48
Abstraction
-A Class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-
abstract methods (method with body).

Abstraction in Java

-Abstraction is a process of hiding the implementation details and showing only functionality to the user.

-Another way, it shows only important things to the user and hides the internal details for example sending sms, you
just type the text and send the message. You don't know the internal processing about the message delivery.

-Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

49
Abstract Classes
• A class must be declared abstract when it has one or more abstract methods. A method is declared abstract
when it has a method heading, but no body – which means that an abstract method has no implementation code
inside curly braces like normal methods do.
• -Abstract classes in Java are classes which cannot be instantiated, meaning you cannot create new instances of
an abstract class. The purpose of an abstract class is to function as a base for subclasses.
• -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

• Properties of abstract classes

1. Must contain at least one abstract method

2. Can contain normal methods, variables and constructors

3. Cannot be instantiated but upcasting can occur

4. Can contain constants

50
Abstract Classes
abstract class ClassName

...

abstract Type MethodName1();

Type Method2()

// method body

} }

51
Example
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

52
Example

class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
53
Example 2
abstract class Bank{

abstract int getRateOfInterest();

class SBI extends Bank{

int getRateOfInterest(){return 7;}

class PNB extends Bank{

int getRateOfInterest(){return 7;}

class TestBank{

public static void main(String args[]){

Bank b=new SBI();//if object is PNB, method of PNB will be invoked

int interest=b.getRateOfInterest();

System.out.println("Rate of Interest is: "+interest+" %");


54
}}
Practice Question
Given the following diagram

Implement the concept of abstraction for classes Mercedes Benz, Mazda and Nissan classes.

55
Java Interfaces
• Using interface, we specify what a class must do, but not how it does this.

• The objective is to attempt to achieve multiple inheritance

• Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the
interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly
public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated
but upcasting is allowed

• Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces.

• Interfaces have the following properties

1. Can contain constants

2. Instance variable should be initialised

3. Methods are declared without a body (abstract methods) and can either be declared with or without the abstract keyword

4. Implementing classes should declare the methods with a public keyword

5. Static methods are not allowed in an interface

56
Java Interfaces
• Using interface, we specify what a class must do, but not how it does this.
• The objective is to attempt to achieve multiple inheritance
• Interface can be used to define a generic template and then one or more abstract classes to define partial
implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can
only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface
like that of an abstract class cannot be instantiated but upcasting is allowed
• Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces.
• Interfaces have the following properties
• Can contain final variables, which must be initialized with values.

1. Instance variables should be initialised

2. Methods are declared without a body (abstract methods) and can either be declared with or without the abstract keyword

3. Implementing classes should declare the methods with a public keyword

4. Static methods are not allowed in an interface

5. One class can implement any number of interfaces.

6. An abstract class can implement an interface

7. An interface can implement another interface using the extends keyword

57
Java Interfaces

Interface Format

Syntax :

[Access-specifier] interface interface-name

Access-specifier return-type method-name(parameter-list);

final type var1=value;

datatype var2= value;

Where, Access-specifier is either public or it is not given(DEFAULT).

• When no access specifier is used, it results into default access specifier and if interface has default access specifier then it is only
available to other members of the same package.
• When it is declared as public, the interface can be used by any other code of other package

58
Java Interfaces Examples

interface Item

static final int code = 100;

static final String name = "Fan";

void display ( );

interface Area

static final float pi = 3.14F;

float compute ( float x, float y );

void show ( );

59
Java Interfaces Examples
interface religion

String city = new String("Amritsar");

void greet();

void pray();

class gs implements religion

public void greet()

System.out.println("We greet - ABCD");

public void pray()

System.out.println("We pray at " + city + " XYZ ");

} }

60
Java Interfaces Examples
class iface1

public static void main(String args[])

gs sikh = new gs();

sikh.greet();

sikh.pray();

61
Java Interface and Multiple Inheritance
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();

62
Java Interface Inheritance
nterface Printable{

void print();

interface Showable extends Printable{

void show();

class Testinterface2 implements Showable{

public void print(){System.out.println("Hello");}

public void show(){System.out.println("Welcome");}

public static void main(String args[]){

Testinterface2 obj = new Testinterface2();

obj.print();

obj.show();

63
Java Interface extending another interface
interface Area{

double length=18, width=20;

double calcArea();

interface Paintcost extends Area{

double paint(double area);

class Testinterface2 implements Paintcost{

public double calcArea(){

return length *width;

public double paint(double area){

area= calcArea();

return area*70;

public class Samz {

public static void main(String[] args) {

Testinterface2 obj = new Testinterface2();

obj.calcArea();

System.out.println(obj.paint(obj.calcArea()));

} 64
Difference between abstract class and interface

65
Aggregation
• If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
• Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one
more object named address, which contains its own informations such as city, state, country, zipcode etc. as
given below.
• Aggregation is meant to promote Code Reusability.

Example of Aggregation

66
Aggregation Example 1
class Operation{

int square(int n){

return n*n;

class Circle{

Operation op;//aggregation

double pi=3.14;

double area(int radius){

op=new Operation();

int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).

return pi*rsquare;

public static void main(String args[]){

Circle c=new Circle();

double result=c.area(5);

System.out.println(result);

}
67
Aggregation Example 2
In this example, Employee has an object of Address, address object contains its own informations such as city, state,
country etc. In such case relationship is Employee HAS-A address.

public class Address {

String city,state,country;

public Address(String city, String state, String country) {

this.city = city;

this.state = state;

this.country = country;

public class Emp {

int id;

String name;

Address address; //aggregation

public Emp(int id, String name,Address address) {

this.id = id;

this.name = name;

this.address=address;

68
Aggregation Example 2
void display(){

System.out.println(id+" "+name);

System.out.println(address.city+" "+address.state+" "+address.country);

public static void main(String[] args) {

Address address1=new Address(“Harare",“Central",“Zimbabwe");

Emp e=new Emp(800,“Java",address1);

e.display();

69
Arraylist
-An arraylist is a special type of array which stores elements of different
data types.
-The data types are of wrapper class types
-A ArrayList is like an array of Objects, but...
-Arrays use [ ] syntax; ArrayLists use object syntax
-An ArrayList expands as you add things to it
-Arrays can hold primitives or objects, but ArrayLists can only hold
objects

70
Arraylist
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

71
Arraylist
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

72
Generic Programming
• Generics can be applied to the follwing

1. Arraylists 2. Methods 3. Classes

Wrapper Classes
• Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.
• Autoboxing and unboxing feature converts primitive into object and object into primitive automatically.
The automatic conversion of primitive into object is known and autoboxing and vice-versa unboxing.
• One of the eight classes of java.lang package are known as wrapper class in java. The list of eight wrapper
classes are given below.
• Java won’t let you use a primitive value where an object is required--you need a “wrapper”
– ArrayList<Integer> myList = new ArrayList<Integer>();
– myList.add(new Integer(5));

• Similarly, you can’t use an object where a primitive is required--you need to “unwrap” it
– int n = ((Integer)myArrayList.get(2)).intValue();

73
Generic Programming
Wrapper class Example: Primitive to Wrapper
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
Wrapper class Example: Wrapper to Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}} 74
ArralyLists and Objects
Java lambda expression can be used in the collection framework. It provides efficient and concise way to

iterate, filter and fetch data.

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

class Product{

int id;

String name;

float price;

public Product(int id, String name, float price) {

super();

this.id = id;

this.name = name;

this.price = price;

//add toString method

}
75
Java Lambda Expression Example: Collections Framework
public class LambdaExpressionExample10{

public static void main(String[] args) {

List<Product> list=new ArrayList<Product>();

//Adding Products

list.add(new Product(1,"HP Laptop",25000f));

list.add(new Product(3,"Keyboard",300f));

list.add(new Product(2,"Dell Mouse",150f));

Int n = list.size();

for(int i=0; i<n; i++){

System.out.println(liist.get(i). toString());

76

You might also like