Java Concepts
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a “blueprint” for creating objects.
To create a class, use the keyword class
:
Create a class named MyClass
with a variable x:
public class MyClass {
int x = 5; //Global Variable
}
Objects can be created within classes, like so:
public class MyClass {
int x = 5; //Global Variable
public static void main(String[] args) {
MyClass myObj = new MyClass(); //Object
System.out.println(myObj.x); //Output Variable 'x'
}
}
Here, main() is a function with no parameters.
The 4 Principles of OOP
- Abstraction.
Abstraction means using simple things to represent complexity. We all know how to turn the TV on, but we don’t need to know how it works in order to enjoy it. In Java, abstraction means simple things like objects, classes, and variables represent more complex underlying code and data. This is important because it lets avoid repeating the same work multiple times.
- Encapsulation.
This is the practice of keeping fields within a class private, then providing access to them via public methods. It’s a protective barrier that keeps the data and code safe within the class itself. This way, we can re-use objects like code components or variables without allowing open access to the data system-wide.
- Inheritance.
This is a special feature of Object Oriented Programming in Java. It lets programmers create new classes that share some of the attributes of existing classes. This lets us build on previous work without reinventing the wheel.
- Polymorphism.
This Java OOP concept lets programmers use the same word to mean different things in different contexts. One form of polymorphism in Java is method overloading. That’s when different meanings are implied by the code itself.