Classes in Java

Classes in Java

In Java, every object (classes) is manipulated through a reference

This reference saves the identifier of the object

And is responsible for sending messages to the object associated

The type of the reference indicates what type of messages you can send

Access modifiers

When you create classes, the need arises to indicate the use of their attributes and methods

Some attributes will be internal:

  • Must not be modified

  • It is not necessary to know of its existence

The same goes for methods:

  • Should not be invoked from outside the class

  • Do not need to know about its usefulness

The access modifiers control the visibility of class members

Indicate which of them are of interest to the outside

Java offers four access modifiers:

  • private

    is visibility more restrictive

    Only allows the invocation from the class itself

  • public

    is visibility less restrictive

    Enables the invocation from any class

  • package

    is the visibility by default

    Only allows the invocation from the classes that they belong to the same package

  • protected

    is the visibility associated with the inheritance

    Only allows the invocation from derived classes

Builders

When a class does not declare any constructor, it automatically creates a default constructor

In the example the constructor has been called from the main method and is responsible for leaving the object in an initial state in which we can work with him

Since we haven't created the constructor, the default constructor was automatically used

In the example, we've defined a class called Person that has only the attribute name that is private

The constructor was used to initialize it and to access it (as it is private it is not directly accessible) the get and set methods have been added

In case you have not used the constructor to initialize it with new, by using p we would have obtained a value null, since the object would not yet be defined in memory

To refer to an attribute of the class itself, we use the reserved word this

In this case, it has been used to refer to the attribute name

Constructor with parameters

When we need to add external information, we can use parameter builders

A constructor can declare the parameters that are needed to create the object

This example is very similar to the previous one, however we now have two constructors, a default constructor and a parameterted constructor

In the event that we have the same name in a parameter and an attribute, we can distinguish them if we use the reserved word this

We did with the parameter name and the attribute name, when using this have become unambiguated

A constructor can also be overloaded, that is, it receives different types of arguments to have different behavior

In this example we have defined classes Point and Rectangle

By defining multiple constructors with parameters of different types to the class Rectangle

So we have overloaded the constructor to be getting different results in the main method

Attributes static

A class describes the attributes of each object (instance attributes)

Sometimes you need attributes that are shared by everyone: that remain to the class

The reserved word static declares a class attribute

In the example you have declared an attribute static of type int, it's not a class but as you can see you can also use primitive types

To access the attribute static we've given you the name of the class, in this case A

There is No need any class instance to be able to access the attribute

It is created when you load the class and initialize with the values from the default constructor

In the example, we have used the classes Timer and A initializing their attributes in a block static

With static should not create new objects because they are back on track with each new instantiation

The class attributes are initialized using a block static

The blocks static running to load the class

Can be considered as a builder most of the class

In this example I've reduced the code to use an equivalent alternative to initialize in the declaration

Static methods

In the same way that there are attributes static there are methods static

Recommended for use with utility methods that are not performed on any object but about primitive types

For example the class Math it offers the methods static sqrt, random, pow, etc

Are declared by using the word static

In the example you have declared the method static f in the class A

The class name is used to invoke them, in this case the class A

A method static you can only access:

  • attributes static

  • other static methods

In the example a reference has been added to the method static g what that allows us to access the elements of the instance of the class A without being static

Keep in mind that to access instance items must obtain a reference to previously

Inheritance

A derived class can add new operations (expand the number of messages that the object understands)

In the example you have created the classes A and B

As B inherited methods A y por tanto, podía usar methodA without problems

However, A non inherited methods B, that's why it gave us an execution error

In the example we have used a derived class to redefine operations

Redefining one method is to give a different implementation to the same message (which will be treated by another method)

It is important not to confuse the overhead of a method with its redefinition

In the example, has redefined the method methodA of the class A in the class B, reusing it by replacing its implementation

It has been used the reserved word super to refer to the methods of the base class

You can also use the reserved word super to refer to the attributes of the base class

In the example there is a base object Vehicle, two derivatives Car and Bike

A fundamental aspect of inheritance is the relationship between the base type and the derived type

The derived class has at least the operations of the base class

That is, an object of the first class understands all the messages that an object of the second class might understand

Therefore, any reference of the base type can point to an object of the derived type (since it understands all its messages)

Polymorphism

Inheritance allows different classes to share a common set of operations (those in the base class)

Dynamic binding allows that even if two objects accept the same messages they can perform them differently

In the example we can see that thanks to polymorphism, even though v is of type Vehicle it takes into account the type of object pointed

It is important to differentiate the two types that participate in sending a message:

  • The type of reference

    it is the one that determines the messages that it can transmit to its associated object

    Therefore, it can only be associated with objects that understand at least those messages (objects of the same type or of a derived type)

  • The type of the associated object

    it is the one that determines which method is the one that dispatched the message received

Constructors and inheritance

The constructors cannot be inherited

In the example we have declared two constructors for the class A and then it has been inherited in the class B

When you try to use the constructor with integer parameter will give us an error because B did not have an appropriate constructor though A yes that was

A class you can only use the constructors that declare

If you have not declared, none will be assigned the default constructor

In the example we have declared two constructors for the class A and then it has been inherited in the class B

But on this occasion it has made a call to the default constructor of the base class within the constructor of the derived class

Some constructor of the base class is required to be invoked (to ensure its state)

By super you can select the proper builder

super can only appear once and must be the first line of the constructor

Will support only the parameters that support the constructors of the base class

Abstract classes

An abstract class is one which has one or more abstract methods

An abstract method is one that has not been implemented in the base class

Your code will have to be provided in each of the derived classes

To define a class as abstract using the reserved word abstract

In the example we have defined the abstract class Vehicle with two abstract methods

As can be seen, methods are also defined using the reserved word abstract

Abstract classes have the restriction that they cannot be instantiated (because they have undeployed methods)

If a derived class does not redefine all abstract methods, it will in turn be an abstract class

Creating abstract classes:

  • Identify the common operations that have to have objects to manipulate

  • Create with them an abstract class base

  • Identify the operations to redefine and give an implementation to the rest

Use of abstract classes:

  • Their only goal is the derivation

  • The class derived will have to implement the abstract methods

  • Others may be inherited, replaced or expanded

Classes end

You may want a class to be un derived (for security reasons, you do not want anyone to be able to replace it with a derived class)

It uses the reserved word end so that the class can not be derived

In the example we have tried to inherit the class B the class A that was end

As we have defined A as end the interpreter will not allow you to have inherited classes

In the example we have defined a final method and one that is not

There is also an intermediate level: that can be derived from the class but not certain methods

A method you can also use the reserved word end

A final method cannot be redefined

In the example we tried to modify a final attribute, the interpreter will give us an error

Make a class or method final is a major constraint

Should only be done in special situations and putting the utmost care

A final attribute cannot be modified once it has been started

In the example, we have defined two variables called x as a final

If the value of the final attribute is the same for all instances, it is wasting space in memory

In this example, we have used constant variables to solve the problem of the previous example

In Java, constants are declared by combining the reserved words static followed by end

Constants do not take up memory and by convention, they are usually defined with a capitalized name

Downcasting

When a class is not derived explicitly from another class then derived implicitly from the class java.lang.Object

The class Object it's not a primitive type, but it's the class from which all the language classes derive and those that the programmer believes

However, you don't need to use the reserved word extends because it implicitly drifts

Therefore, all kinds of Java is a Object and will inherit the methods of this

Some of the outlined methods of the class Object:

  • boolean equals(Object)
  • void finalize()
  • int hashCode()
  • String toString()

There are occasions in which it is known with certainty that the object is of the appropriate class

In these cases you may be able to force the assignment using a cast

In the example we have used the classes Vehicle and Canoe that inherits from it

To then make a declaration of a Vehicle v for that we have used the constructor Canoe

And has been declared a Canoe c for which the type was previously known (Canoe) por lo que se ha realizado un cast

The cast checks that the object is of the appropriate class and performs the assignment

In the event of not being of the appropriate class or is not able to perform the assignment will throw an exception ClassCastException

Operator instanceof

The operator instanceof allows you to find out if an object belongs to a certain class

In the example, has carried out two checks with instanceof

When we tested with Object will always return True because it is a supertype of the class of the instance

When we tested with Canoe we have checked if the cast can be applied

In this way we avoid having to handle the exception ClassCastException

Interfaces

Interfaces, like classes, are a way to create objects

They are characterized by only one behavior (and/or constants)

  • Have No attributes

  • Do not have associated code for methods

Are defined with the reserved word interface in a similar way as is done with the classes

In the example we have defined the interface anInterface with the methods method1 and method2

Similar to abstract classes, because they have no implementation it is possible to instantiate the interface

You can only use it to create new data types (other classes or interfaces)

In this example it has implemented the interface anInterface heredandola in the class aClass

When the class aClass inherited methods anInterface it has become a subtype of that interface

For that reason we must give them an implementation in the class, since sinó we would be obliged to declare it abstract

But precisely because he has used an interface, the interpreter will show us an error message telling us which specific methods have not been implemented

Differences between class and interface

Class:

  • Type that extending it by inheritance results in its behavior and implementation (both attributes and its methods)

  • Advantage: Less coding when creating new subtypes as its behavior comes to its implementation

  • Drawback: It can only be derived from one of them, multiple inheritance is not allowed

Interfaces:

  • Type that extending it by inheritance gets only its behavior (description of methods)

  • Advantage: You can inherit multiple interfaces without conflicts

  • Drawback: There is hard-coding the implementation of each method for each subtype inherited