Inheritance , encapsulation – OOP(2)

Object Oriented Programming is one of the important types in modern programming. It considers the things related to data as Object and Object’s properties.

In Java, a class can be defined as an object. The functions, properties are considered like how such object behaves. In this article, I would like to introduce the fours main characteristic of OOP programming in Java, including Inheritance, encapsulation, polymorphism and abstraction.

Inheritance

The inheritance allows the developer to build the new classes (subclass) from what was defined in another class (parent class). In another word, we can reuse what was built.

The following example about how the subclass inherited what defined in the parent class.

public class testInheritance{
	public static void main(String[] args){
		Dog dog = new Dog("dogA");
		dog.eating();
		System.out.println(dog.getNumberOfFeet());
		System.out.println(dog.makeSound());
}

//Class animal is parent class which is used to define the
//characteristics of one animal including number of feet, sound
class Animal{
	private int numberOfFeet;
	private String sound;
	public Animal(int numberOfFeet, String sound){
		this.numberOfFeet = numberOfFeet;
		this.sound = sound;
	}
        int getNumberOfFeet(){
		return numberOfFeet;
	}
	String makeSound(){
		return sound;
	}
}
//class Dog inherits from class Animal but has new properties is Dog's
// name
class Dog extends Animal{
	private String name;
	public Dog(String name){
        //super() refers to the parent class's constructor 
        // have to declare the at the first line in sub 
        // class's constructor.
		super(4,"Wove,.."); 
		this.name = name;	
	}
	void eating(){
		System.out.println(name + " is eating");
	}
}
 dogA is eating
 4
 Wove,.. 

Encapsulation

Encapsulation property will protect the code from the outside accessing such as change the value, or seeing what contained in a class.

For the code above, the properties of Animal class will not be access or mutation from another class; for example, if one function or a variable want to get the value numberOfFeet which was declared as private in the Animal class, it has to access via the method getNumberOfFeet().

Dog a = new Dog("pop");
a.numberOfFeet; //not allowed
a.getNumberOfFeet(); //must be

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: