Java Intro Tutorial-EN
Hello everyoneđź‘‹
Since I could not touch on the codes in detail in my previous oop-functional and procedural writing, I wanted to touch on the concept of OOP with a short review of Java. Let’s start. 💪
Variables(Field or Attribute):
We keep data with variables. Let’s first understand why we use variables.
Let’s say that attendance will be taken at the school, first the teacher checks the number of students in the classroom, then the principal checks it, and then the total number of students is entered into the system. Let’s say the number of students we have is 20. Later, another student came to the class, but our list had already gone to the principal. We would have to go and add that 1 student to our attendance list one by one and update it to 21 (in every place where control is provided and every student who comes). That would be a huge inconvenience, wouldn’t it?
At this point, we will be using variables.
✳️ DRY(Don’t Repeat Yourself): The Object-Oriented design principle means not repeating yourself. This means keeping the variables in one place and updating the entire project with a single line change in case of any update.
We used the address variable in many parts of the project, and assuming an address change situation is required, all we need to do in such a scenario is to fix the address line. Otherwise, we would have to manually update addresses one by one wherever we write address data.
Data Types:
Java is a statically typed programming language. This means that all variables must be declared before they are used. So we need to specify the type and name of the variable.
Data types specify different sizes and values ​​that can be stored in the variable.
It is used to define the data that we will store in the variable while defining a variable.
There are two types of data types in Java:
1. Primitive data types:
There are 8 primitive types. These:
✳️boolean, char, byte, short, int, long, float ve double.
2. Non-primitive data types:
There are 3 non-primitive types. Non-primitive data types include Classes, Interfaces, and Arrays.
Not: Strings are reference types as an exception.
✳️These two data types use areas of memory called stack and heap. Value types are kept in the stack, while reference types are kept in the heap. Stack is faster than heap.
✳️For Primitive types;
number1 is set to number2 and its residual value is written to the stack as 40. Updating number2 after this assignment has no effect on number1, only the new value of number2 is updated to 90 (as in the figure).
✳️For Non-primitive data types;
The situation here is that the address of numbers1 is equal to the address of numbers2. Suppose there are addresses 1 and 2. The first numbers1 list is kept at address 1, while the numbers2 list is kept at address 2. When we set numbers1 to numbers2, the address of numbers1 is now address number 2.
Since address 1 is no longer variable, it is cleaned with the Garbage Collector.
While the data in the Stack memory is deleted immediately, it is up to the Garbage Collector to delete the data in the Heap memory.
Conditions and if Blocks:
We use if blocks to branch our projects according to a certain condition.
Java supports logical conditions in math.
Switch/Case Blocs:
We use switch blocks to choose one of the many code blocks to execute.
For Loops:
You can use a for loop when you know exactly how many times you want to loop through a block of code. The for loop takes 3 parameters.
Syntax:
Arrays:
It is used to define multiple variables of the same type. They are reference types.
The index number starts from 0.
✳️ The []
operator is placed at the end of the array name and this operator determines the index numbers.
String:
String replaces char arrays.
String is a class, not a primitive data type. It has its own variables and its own methods.
Note: Space is also a character.
String class has very important role in java. Therefore, the String class defined in the Java API has more than 10 constructors and more than 100 methods (concat, replace, containers…). I will not mention them in this article.
Variable Arguments (Varargs):
A variable-length argument is indicated by an ellipsis (…
). We can use varargs
when we do not know how many of a particular type of argument will be passed to the method. The important thing here is that if we are going to use a varargs as a parameter, we should write it as the last parameter.
myMethod (int i, String ... strings) // truemyMethod (String ... strings, int i) // false
In Java, classes are written as PascalCase and methods are written as camelCase. (Naming Convention)
Methods:
Methods are code broken down into small chunks. It is quite useful to avoid code duplication.In this way, they provide a great advantage in terms of code readability and code performance. Methods are functions
, procedures
, etc., according to the programming languages ​​they are used in. they may be called.
The methods are examined in 2 parts, I will give a short example without going into details.
🟣Parameterized Methods:
The method named addToCart, which takes a Product
object as a parameter, has been created as an example to perform the process of adding products to the cart.
🟣Non-Parameterized Methods
In this example, an example of a non parameterized method (deleteCart) that performs the cart deletion is given.
Class:
Classes are reference types.
They hold common operations and variables (field, attribute).
They start with a capital letter.
In order to use a class, we need to initialize
it. So we have to create object. To create an object of Main
, specify the class name, followed by the object name, and use the keyword new
.
In Java, classes cannot be made Static
, but nested classes can be made static inside.
Encapsulation:
For encapsulation, we make the data private and apply the getter and setter methods to access this data. You can refer to this article for a detailed explanation.
We created a Product class and added properties to it. In order to access it, we added the getter and setter methods and finished our task here.
When using the Product
class in Main, we either create an instance from a parameterized constructor like product1 or create an instance from a non parameterized constructor like product2 and use it.
Inheritance:
Basically, it allows us to collect the common fields and methods in a project and inherit from that class without having to rewrite the fields and methods that are common in a project.
Here I created a very basic example because I want to transfer it in a simple way. We have a common Customer class and this class holds the properties that every customer should have, so we will take Customer as the base class.
Individual and corporate customers, apart from their own features, can also include base class features by extending from the base class. You can check github for details of the code.
Polymorphism:
It is the case that reference types with an inheritance between each other keep references to each other.
In other words, it is a method of using inheritance or implementations in a different way over an inherit or implemented object. In general, we use polymorphism with interfaces. Now let’s try to understand through an example.
Let’s say we are working with more than one database, in our scenario each customer is kept in MySQL, MSSQL and Oracle databases according to specific requirements.
Here I will create an interface and give a simple customer add feature.
Let’s implement the ICustomerManager
interface in MySQL class. Let’s print a simple log.
In my Manager class, I will give the ICustomerManager
interface as a parameter, so I can implement the addCustom
method on the database I want.
Now let’s finally see how to use this in the main class.
As you can see, we have created a CustomerManager
object and specified that we want to add customers to the MySQL database as a parameter. When we run it, we can see the log we have printed in the MySqlDbManager
class.
Abstract:
It allows us to add mandatory methods, so our method is forced to be populated in every extends
class (as in the picture). It is used with the abstract
keyword. It cannot be created with new
.
One of the most important things in coding is to avoid if’s. Let’s imagine that we are doing a database management and customers’ data can be in different databases. If we were to write this code with if
, it would be as follows, which is not a very good method.
We can create an abstract base class and derive all databases we want from this class. In this way, code review and editing operations will become much easier. I will share only 1 example class MsSqlDbManager
here, you can check my github account for a details.
Now that we are extending, let’s create a customer management class and associate it with our base class. Thus, we will run the whole project through a single class and we will not be dependent on any other class. In our main class, we can now operate on the database we want. Main can of course be written more effectively, but now I used it this way in order not to distract the subject.
Interface:
Interfaces are not considered classes, but they hold references like regular classes or abstract classes. They cannot be used with new
.
As a naming convention, “I” is added in front of the class name, this is not a requirement, but it is generally used like this.
Note: A class can implements more than one interface.
Note: An interface can extends but not implements another interface.
Again, let’s set up the interface structure with the database example. First we will create an interface(ICustomerManager)
so that it acts as a template.
Let’s create the classes of the databases with our customer data, which we will implement later. Again, I’m only adding one.
Finally, I add the database I want in the main and run it. This is the general logic in its simplest form.
I hope it was useful. See you in my next post. 🙋