Objects In Day 11 Of One Month Of Java
We Are Moving Into The Hard Stuff In Java With OOP
Well the above image is the first image I got when I entered Object Orientated Programming. I used it for this post because it feels like I am starting all over again. I know the basic concepts of Object Orientated Programming but implementing them in Java, the correct way, will be a whole new story. With my momentum slowing, I hope I can still get through the month.
Java And OOP
Object-oriented programming is a programming concept based on objects, where each object contains both data and methods. This programming methodology brings together data and its behaviors(methods) into a single location which is the object.
An Object is a collection of states(data) and its behaviours(methods), for example:
Object: Cat
State: Colour, breed, size
Behaviour: walks, plays, purrs
States are represented as instance variables
Behaviors are represented as methods in the class
Characteristics of an Object
Abstraction: This is where you show relevant data and hide unnecessary details of an object from a user
Encapsulation: This means creating object state(fields) and behavior(methods) together. If you are creating class, you are doing encapsulation.
Inheritance: This is the process by which one class acquires the properties and functionalities of another class.
Polymorphism: This is a object oriented programming feature that allows us to perform a single action in different way.
Message passing:
What is a Class in OOP
This is the blue print you use to create objects from, for example in our cats example, it would not be any specific cats, it would simply be a recipe to create the cat object. We use a constructor to provide properties to the objects.
What is a constructor
It looks like a method, but its not.
The name is the same as the class and it doesn't return any values
<ClassName> <NameInApplication> = new <ConstructorName>
Code For The Day
1 public class Cats {
2 String catName; // fields
3 int catAge;
4
5 Cats(String name, int age) { // Constructor
6 this.catName = name;
7 this.catAge = age;
8 }
9 public static void main(String args[]) {
10 Cats obj1 = new Cats("TimTam", 16); // Creating the objects
11 Cats obj2 = new Cats("Mittens", 4);
12
13 System.out.println(obj1.catName+" "+obj1.catAge); // Accessing the data
14 System.out.println(obj2.catName+" "+obj2.catAge);
15 }
16 }
Output
java Cats
TimTam 16
Mittens 4