Java Core Tutorials

Object Oriented Programming in Java

Pinterest LinkedIn Tumblr

Java is an object-oriented language, which means that it has constructs to represent objects from the real world. Each Java program has at least one class that knows how to do certain things or how to represent some type of object.

CLASSES AND OBJECTS

Classes in Java may have methods and fields (also known as attributes). Methods represent actions or functions that a class can perform. Up until Java 8, every function had to be represented as a method of some class. Lambda expressions give more freedom to functions, but for now the focus is on the Java foundation classes, methods, and fields.

Let’s create and discuss a class named Car. This class will have methods, describing what this type of vehicle can do, such as start the engine, shut it down, accelerate, brake, lock the doors, and so on. This class will also have some fields: body color, number of doors, sticker price, and so on.

class Car {

    String color;
    int numberOfDoors;

    void startEngine() {
        System.out.println("Start engine");
    }

    void stopEngine() {
        int tempCounter = 0;
        System.out.println("Stop engine");
    }
}

Car represents common features for many different cars: All cars have such attributes as color and number of doors, and all of them perform similar actions. You can be more specific and create another Java class called RacingCar. It is still a car, but with some attributes specific to the model created for RacingCar. You can say that the class RacingCar is a subclass of Car, or, using Java syntax  RacingCar extends Car.

class RacingCar extends Car {
    boolean rocketAccelerator = true;
    int velocity;
    String manufacturer;

    void race() {
        velocity = 200;
        System.out.println("Race");
    }
}

RacingCar not only have all attributes of Car but also have some of other attributes such as: rocketAccelerator, velocity,  manufacturer. Besides inherited all methods from Car RacingCar have a other method: race()

Creating objects, also known as instances, based on classes is the equivalent of building real cars based on blueprints. To create an instance of a class means to create the object in the computer’s memory based on the class definition. To instantiate a class, you declare a variable of this class’s type, and use the new operator for each new instance of the car:


RacingCar car1 = new RacingCar();

RacingCar car2 = new RacingCar();

Now the variables car1 and car2 can be used to refer to the first and second instance of the RacingCar.

The statement new RacingCar() creates the instance of this class in heap memory. In the real world, you can create many cars based on the same specification. Even though they all represent the same class, they may have different values in their attributes some of them are red and some yellow, some of them have two doors whereas others have four, and so on.

Declaring Variables

Java is a statically typed language: A program variable must be declared (given a name and a data type) first, and then you can assign them values either at the time of declaration or later on in one of the class methods. For example


int a = 12;

String message = "Welcome";

Final Variables

To store the value that never changes, you need to declare a final variable (or constant); just add the keyword final
to the declaration line. By Java Naming convention, you should declare Final variables in upper case. For example:

final String COUNTRY = “US”;

Privimitive Data Types

When you’re declaring a class, you create a new data type and can declare variables of this type as you saw above
with the class Car. But these are not a simple data type as they can include fields and methods describing the
object of this type. On the other hand, Java has predefined data types for storing simple values, such as an integer
number or a character.  There are eight primitive data types in Java.

Primitive Data TypeSizeDescription
byte-128 to 127Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.
Example: byte i = 110;
short-32,768 to 32,767Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer
Example: short a = 10;
int-2,147,483,648 to 2,147,483,647Integer is generally used as the default data type for integral values unless there is a concern about memory.
Example: int a = 1000;
long-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807This type is used when a wider range than int is needed
Example: long b = 100000000L;
float1.40129846432481707e-45 to 3.40282346638528860e+38Float is mainly used to save memory in large arrays of floating point numbers.
Example: float total= 2.3f;
double4.94065645841246544e-324d to 1.79769313486231570e+308dThis data type is generally used as the default data type for decimal values, generally the default choice
Example: double i = 100.14;
booleantrue/falseThis data type is used for simple flags that track true/false conditions
Exmaple: boolean status = true;
char0 to 65,535Char data type is used to store any character
Example: char letter = ‘b’;


VARIABLE SCOPE

  • If you declare a variable inside any method or a code block surrounded with curly braces, the variable has a local scope( for example tempCounter, velocity). A local variable is accessible within the method only after the variable is declared, and only within the block in which it is declared. When the method completes its execution, all local primitive variables are automatically removed from stack memory. If a variable was pointing to an instance of an object (for example,car1), the corresponding object instance is removed from heap memory by Java‘s Garbage Collector (GC).
  • If a variable has to be accessible from more than one class method, declare it on a class level (for example: color, numberOfDoor).  They can be shared and reused by all methods within the class, and they can even be visible from external classes.
  • If a variable is declared with a static qualifier it will be shared by all instances of the class. Instance variables (without static) store different values in each object instance.

Example

Declaring a Tax Class

public class Tax {
    double grossIncome;
    String state;
    int dependents;

    public double calcTax() {

       return 234.55;
    }

}
  • Gross income is not always an integer number, so use the double data type, as it’s a number with a decimal point. You could use float instead, but using double enables you to be ready to process larger incomes.
  • You also need to know what state the person lives in; taxation rules vary by state.  Use the data type String for storing text data.
  • Add one more attribute for dependents of the taxable person. Integer works just fine here €” a person can’t have two-and-a-half dependents.
  • The calcTax() method signature tells the following:
    • Any external class can access this method (public).
    • This method returns a value of type double.
    • The name of the method is calcTax.

Declaring a TestTax Class

class TestTax{
     public static void main(String[] args){

            Tax   t = new Tax(); // creating an instance

            t.grossIncome= 50000;  // assigning the values
            t.dependents= 2;
            t.state= "NJ";

            double yourTax = t.calcTax(); //calculating tax 

           // Printing the result
           System.out.println("Your tax is " + yourTax);
     }
 }

The class TestTax should be able to perform the following actions:

  • Create an instance of the class Tax.
  • Assign the customer’s data (gross income, state, dependents) to the class variables of the class Tax.
  • Call the method calcTax().
  • Print the result on the screen.

The method main() is an entry point to the tax-calculation program.  This method creates an instance of the class Tax, and the variable t points to a place in your computer’s memory where the Tax object was created.  The method calcTax() still returns the hard-coded value.  The last line just displays the result on the system console.

I'm a full stack developer. I have experiences with Java, Android, PHP, Python, C#, Web development...I hope website https://learncode24h.com will help everyone can learn code within 24h and apply it in working easily.

Write A Comment