Norzagaray College: Abstraction
Norzagaray College: Abstraction
Principles of OOP
Abstraction
With abstraction, you can hide the internal workings of an object and only show the features the user needs
to know about. Java provides two ways to implement abstraction: abstract classes and interfaces. With
abstract classes, you can achieve partial abstraction, while interfaces make total (100%) abstraction possible.
Example
void label() {
System.out.println("Animal's data:");
}
}
void move() {
System.out.println("Moves by flying.");
}
void eat() {
System.out.println("Eats birdfood.");
}
}
myBird.label();
myBird.move();
myBird.eat();
}
}
class TestFish {
public static void main(String[] args) {
Animal myFish = new Fish();
myFish.label();
myFish.move();
myFish.eat();
}
}
Output :
(TestBird output)
Animal's data:
Moves by flying.
Eats birdfood.
Animal's data:
Moves by swimming.
Eats seafood.
Inheritance
Inheritance allows us to extend a class with child classes that inherit the fields and methods of the parent class.
It’s an excellent way to achieve code reusability. In Java, we need to use the extends keyword to create a child
class.
class Bird {
public String reproduction = "egg";
public String outerCovering = "feather";
class TestEagle {
public static void main(String[] args) {
Eagle myEagle = new Eagle();
(Output of TestEagle)
class Animal {
dog1.eat();
dog1.sleep();
dog1.bark();
}
}
I can eat
I can sleep
I can bark
Polymorphism
Polymorphism makes it possible to use the same entity in different forms. In Java, this means that you can
declare several methods with the same name until they are different in certain characteristics. Java provides
us with two ways to implement polymorphism: method overloading and method overriding.
class Bird {
public void fly() {
System.out.println("The bird is flying.");
}
public void fly(int height) {
System.out.println("The bird is flying " + height + " feet high.");
}
public void fly(String name, int height) {
System.out.println("The " + name + " is flying " + height + " feet high.");
}
}
class TestBird {
public static void main(String[] args) {
Bird myBird = new Bird();
myBird.fly();
myBird.fly(10000);
myBird.fly("eagle", 10000);
}
}
( Output of TestBird )
class Animal {
private String name;
private double averageWeight;
private int numberOfLegs;
// Getter methods
public String getName() {
return name;
}
public double getAverageWeight() {
return averageWeight;
}
public int getNumberOfLegs() {
return numberOfLegs;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
public void setAverageWeight(double averageWeight) {
this.averageWeight = averageWeight;
}
public void setNumberOfLegs(int numberOfLegs) {
this.numberOfLegs = numberOfLegs;
}
}
myAnimal.setName("Eagle");
myAnimal.setAverageWeight(1.5);
myAnimal.setNumberOfLegs(2);