Chapter 2.2(OOP Principles) Lecture Iterface (1)
Chapter 2.2(OOP Principles) Lecture Iterface (1)
M
M Class
2
1
methods operate on the
data, Fields/Data
=>It is a the technique
which involves making the 4
M
fields in a class private and
M3
providing access to the
fields via public methods.
Encapsulation
If a field is declared private, it cannot be accessed
by anyone outside the class, thereby hiding the
fields within the class.
For this reason, encapsulation is also referred to
as data hiding.
Encapsulation can be described as a protective
barrier that prevents the code and data being
randomly accessed by other code defined outside
the class.
Example
public class Mammal extends Animal
{
//body
}
Inheritance…
public class Student {
protected String name;
public Student() {
name = “”;
}
public Student(String s) {
name = s;
}
public String getName(){
return name;
}
}
class Animal {
public int numberOfLegs;
public void talk() {
System.out.println("Hello");
}
}
Inheritance Example…
class Dog extends Animal {
public int numberOfFleas;
public Dog() {
numberOfLegs = 4;
numberOfFleas = 10;
}
public void bark() {
System.out.println("Woof woof");
}
public void scratch() {
if (numberOfFleas > 0) numberOfFleas--;
}
}
Inheritance Example…
Dog d=new Dog();
d.bark();
d.scratch();
System.out.println(d.numberOfFleas);
d.talk();
Super keyword
When extending a class you can reuse
the immediate superclass constructor.
Example:
java.lang.System, java.lang.Math
Writing Final Classes and Methods…
A final method cannot be overriden by
subclasses. This is used to prevent
unexpected behavior from a subclass
altering a method that may be crucial to
the function or consistency of the class.
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces
public class Mammal implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels"); }
public int noOfLegs(){
return 0; }
public static void main(String args[]){
Output:
Mammal m = new Mammal(); Mammal eats
m.eat(); Mammal travels
m.travel();
}
}
Abstract vs Interface
Unlike interfaces, abstract classes can
contain fields that are not static and final,
and they can contain implemented
methods.