Java Class And Object With Programming Examples

Classes and Objects:

Java class and object:- You may have heard that Java is an object-oriented programming language. So it also has to be something like objects in Java. Both are correct, but we have not yet discussed it. So let’s start at once. The structures of the objects are And here it is our first class named Rectangle:

declares an int variable, as follows:

int x;

We also declare variables in our class, once with the name width and once with the name height. Both variables are type int, so accept integers as values. Here again the declaration of the two private variables :

private int width;

private int height;

While we use variables declared within functions as local variables, we call them variables whose declaration directly in classes, attributes. We would have a Class property already detected: Classes have attributes. In addition, classes have methods. Methods are functions a class that is used to access its attributes. Use methods i.e. the manipulation or change and the reading out of the respective Attributes. For example, you can use setWidth() to adjust the width of a rectangle and use getHeight() to read out the height of a rectangle. Conclusion: Classes define attributes on the one hand and methods on the other to access these attributes.

Our class declaration would have the structure of a Rectangles. The type Rectangle has been defined. We have is defined by a width and a height, and have set methods to apply to a rectangle can. Now we want to create a concrete rectangle. We want to a specimen, or as they say, an instance of a rectangle have. In short: We need an object! A concrete expression of a class is called an object. So let’s insert as follows specific rectangle to:

rectangle r1 = new rectangle(10, 50);

Our object has the name r1. To the left is in the declaration its type designation, namely rectangle. We assign this r1 new rectangle. We specify the keyword new, which is indicates that – especially for the attributes of a rectangle – new space is reserved. Finally, a very special method which we have defined above and which have the same name carries like our class itself. Again its definition:

This method is a so-called constructor. He will: called when a new instance is created or instantiated and initializes our new object. We surrender as width 10 and as height 50. The respective values are thus assigned to our Attributes. If we wanted, we could also define multiple constructors. for example, we could use a standard or default constructor, i.e. a constructor without parameters. We would have had the Overload constructors, i.e. multiple constructors with different Parameter lists.

To use the object, first, specify the object name. then a period (“.”) and finally the name of the method with which you want to access the object. Here is an example:


This call makes the console more or less attractive drawn with a dashed rectangle.

The attentive reader may now have the impression that I am Engage contradictions: I mentioned earlier that a method to access its attributes. My paint() method, however, accesses the attributes of the class at all not too! Instead, it outputs a rectangle of static size. They have nothing to do with a specific rectangle object. To me, I’m sorry to say that the paint() method is still is not ready. Our final goal should of course be to create a rectangle on a neat graphical interface, not on the console to draw. The width of the rectangle in pixels is determined by the attribute, the height specifies the height attribute. And then fits it again: Our method (paint()) uses attributes (width, height). So consider the current implementation as an Intermediate step.

And by the way, you can’t just overload constructors, as I just pointed out. but also any other method. It would be conceivable for example, a paint() method with a parameter that Defines the color in which the rectangle should be drawn. In this case: could paint() without parameters the rectangle defaults black, and the rectangle could be parameterized using the color parameter in the color. The paint() method would be overload.

The creation of Java objects in the memory:

Identity, state, behavior:

The objects shown in the software have three important Properties:

  • Each object has an identity.
  • Each object has a state.
  • Each object displays a behavior.

These three properties have important consequences: On the one hand, the identity of the object during its life until its death the same and cannot change. On the other hand, data and the program code for manipulating this data as related to each other. In procedural systems, Scenarios such as the following: There is a large memory area on which all subroutines can access somehow. The objects is different because they logically manage their own data and the Monitor tampering.

So object-oriented software development is about to model objects and then program them. The design takes to model objects and then program them. The design takes a central position; large systems are dismantled and always finer.

Please take a look at the following example. This is where our Object r1 of the rectangle type is created and a second Rectangle r2 defined:

rectangle r1 = new rectangle(10, 50);

rectangle r2 = new rectangle(20, 30);

Let’s have the coordinates written on the screen, something like this.

System.out.println(“r1 (” + r1.getWidth() + “, ” + r1.getHeight() + “)”);

System.out.println(“r2 (” + r2.getWidth() + “, ” + r2.getHeight() + “)”);

Then we get the following output:

r1 (10, 50)

r2 (20, 30)

We could now change the width from r1 to 60:


And the repeated output of r1 and r2 results (as expected):

r1 (60, 50)

r2 (20, 30)

But let us do the following:

Rectangle r3 = r1;

A corresponding output of r1, r2, and r3 results:

r1 (60, 50)

r2 (20, 30)

r3 (60, 50)

Now let’s set the width back to 10 for r1:


And we get this output.

r1 (10, 50)

r2 (20, 30)

r3 (10, 50)

Not only the width of r1 has changed to 10, but also that of r3! The reason for this is that r3 is not a copy of r1. It’s a reference to the same object. This means Changes if r1, then r3 also changes, and if r3 changes, then r3 changes also r1. Internally, r1 and r3 refer to the same memory area. Now you may have heard before that there are no pointers or no references, such as C++. The is syntactically also perfectly correct and this fact has the Advantage that programming is simplified in many ways is. However, even if you are a Java programmer, you still need a certain Presentation of references, since in the memory with Java are used. A look behind the scenes brings light into the dark. What actually happens when we write:

rectangle r1 = new rectangle(10, 50);

Basically, two things happen at once in memory. That is why we will split this directive first as follows:

Rectangle r1;

r1 = new rectangle(10, 50);

The first line defines only one pointer to an object of the Rectangle type. A pointer is a memory address. Its size depends on the address bus width. A 32-bit machine has 32-bit pointers, a 64-bit machine has 64-bit pointers, etc. The second line is initially reserved based on the new memory. The amount of memory allocated is determined indirectly by the following Constructor. This is called a rectangle, so it is from the Class Rectangle. The class rectangle has two int attributes, memory must be reserved for two int variables. Then the constructor itself is executed, which in turn initializes the rectangle with the width and the height. Finally, the assignment (“=”) causes the Pointer r1 to refer to the created rectangle. That means: the pointer gets the address of the rectangle object.

java class and object

And so after the second line:

java class and object

Similarly, the creation of the rectangle r2 has this instruction

Rectangle r2 = new rectangle (20, 30);

the following effect in the memory:

java class and object

Should now r be manipulated – the width should be, for example, set to

set the value 60:


is r1 as an alias name for the corresponding pointer see. The pointer is then resolved; i.e. it will be memory jumped to the address the pointer contains, and in our case, the setWidth() method is used to overridden wide attribute with value 60. The following figure shows the result:

java class and object

And now this instruction can also be better understood:

Rectangle r3 = r1;

A pointer r3 to the object already referenced by r1 becomes created. So no new object is created! The key word new is not used! The result looks like this:

java class and object

If the length is now set to 10 at r1:


that same object is modified to which r3 also refers, and this explains that when reading out the width of r3, the value 10 is returned.

java class and object

You can also define the attributes and methods of a class as static. The main() method is such a static method. Static Attributes and methods are identified by the static keyword (Remember: public static void main…).

The peculiarity of static attributes and methods is that they are not bound to an object but only exist once per class. From any (normal) method, you can access a static method or static attribute; However, you may need to a static method of a class no (normal) method and no (normal) method Directly address attribute. That would not be clear. For example, for demonstration purposes, we can Use a static attribute on a rectangle to give each instance a unique number. To do this, consider the following section of a modified rectangle class:

The static attribute maxNr is initialized with 0. At every production of a new rectangle, its attribute is only with the value of maxNr, then maxNr is increased by the value 1. The first rectangle has, therefore, the number 0, the second rectangle has the number 1, the third rectangle the number 2, etc. I want to show you one more thing. To this end, I shall extend the amended Rectangle class:

The program contains an additional static attribute named INTERVAL, which is declared with the keyword final. Thereby is marked as a constant. The value of INTERVAL can no longer be used after initialization during the program run changes. Names of constants are usually capitalized. The program performs a correspondingly frequent instantiation of Rectangle the following output on the screen:

Basically, a class is like a peach

Well, maybe that comparison is somewhat lacking, but at least in structural terms, you can compare a class to a peach. A peach is essentially made of a fairly thick core surrounded by a lot of pulp. The core is inside the pulp

java class and object

outside. In order to get to the core, you have to go through the pulp first. through. Reaching the core directly is not possible. In a class, that’s basically the same thing. The attributes represent The heart of this is that the pulp is in accordance with the methods. To the attributes, you can get from the outside through the methods. Unfortunately, in this context, the Technical term peach principle not enforced. Instead, you talk This is typically from what’s called data encapsulation. Encapsulate the methods their attributes, i.e. the methods control access to their attributes.

For example, We want the length of the rectangle r1 by the method of any object (so we want to get 10 – this is the current value). We, therefore, call the getWidth() method from the class rectangle, which in turn refers to the actual attribute and returns its value. See here again the method getWidth() from the class Rectangle:

In general, communication between objects takes place as follows:

java class and object

In this figure, (1) calls a method of the left object of a class. a method of the right object of another class that (2) accesses its attributes (reads and/or modifies them) and finally (3) returns a value. The last step (3) is optional. Not every method call results in a return value. In such a case, the method call serves only to manipulate the respective attributes.

Java is not quite as rigorous in data encapsulation. You can’t necessarily only via methods of a class to the attributes of these classes. Rather, Java allows us (the programmers) to configure which attributes can be addressed from outside And they don’t. Attributes that may be addressed from outside, are declared with the keyword public. Should attribute only methods of the same class, they shall be with the private keyword.

In our rectangle class, all attributes that were private shall be reported. They must therefore not be addressed from outside. Sun looked like the corresponding declaration:

private int width;

private int height;

Both attributes are private. The same applies to methods: methods can be public or private. All our methods of the class rectangle were public so that it can be addressed from the outside, such as our setHeight() Method:

public void setHeight(int height) {

if (height > 0) this.height = height;


Any private methods could be used exclusively by class internal methods. Moreover, private and public are not the only keywords in Java, which can be used to define so-called visibility.

In addition, there is also the option of protecting protected or do not specify. So far, we only have visibility in the same class and everywhere. In fact, a more finely granular configuration of visibility by specifically subclasses and the affiliation to the same package. What to do with sub-classes, related to inheritance. A package offers the possibility to group several logically related classes. The topic Packages are discussed in more detail towards the end of this section. Attention: Visibility is class-specific and not object-specific! For example, a private method of a particular object cannot only are called by method instances that are applied to the same object. Rather, all objects in the corresponding class have Access to this method. For example, the following class definition is valid:

The method m2() can apply m1() to the object o, although m1 private. The decisive factor for this is that m2() and m1() in the same class. I have presented the so-called elementary data types further on. Now we introduce another data type, the abstract data types. And abstract data types are specified by classes. Specific characteristics or instances of elementary data types variables, instances of classes are called objects. The In both cases, type determines which operations are performed on the variable or the object can be applied. For abstract data types, the operations are determined by the methods of the corresponding class. The operations are defined explicitly (by the programmer). For operations are implicit in the elementary data types (by programming language). For example, an int variable allows an addition (+ operator), a multiplication (* operator), a Incrementation (++ operator), etc. Behavior is exact. This goes so far that Java implicitly throws an exception, if division by 0 is attempted. Another difference between abstract and elementary data types is that abstract types are always indirect, i.e. via references, but elementary types are not. Abstract Types are therefore so-called reference types, whereas directly addressed elementary data types are so-called value types.

Difference between Elementary and Abstract Data Types and why it is necessary:

Elementary and abstract data types are very similar. The former is fixed by Java, the latter can be implemented freely. The only question that arises is why there is a distinction at all is made between elementary and abstract data types or why the elementary data types not also simply as Classes defined and part of the supplied class library from Java are?

The answer is: If every int, every double, every char If a variable were implemented as an object, Java would be significantly slower. The administration of objects is much more complex for the computer than dealing with elementary variables. That is to one on the indirect addressing of objects in Java (you remember the pointers?) and secondly, that operation on elementary data types directly supported by the processor will. This one knows how to add two integers like you divide two floating-point numbers – after all, that’s his task. Would call these basic operations over an additional method instance takes place, the system would be slowed down. This is particularly problematic because in a Java application, not just a few elementary variables exist, but in the basic, all objects on attributes more elementary Data types are based on. The slowdown caused by an implementation using objects adds up quite considerably – that’s why the separation between elementary and abstract data types. Java has also learned from the past in this regard. It has ever existed (at least) one programming language that only was made up of java classes/objects, namely small talk. Straight Here it was found that handling objects for types like int, double, etc. is too slow.

Character (strings):

Strings are something very fundamental in the Program. You actually need them all the time. Still, am I haven’t elaborated on this topic for a valid reason received. While for individual characters (e.g. ‘A’, ‘*’, ‘5’) the elementary Data type char is responsible, you need to deal with Strings (e.g. “Hello World”, “H-7-25”) replace the abstract String data type. So there is a class String, Instances of this class are concrete strings. And there classes and objects could only now be explained, we deal with only now the subject of strings.

Incidentally, in the examples already shown for individual Characters and strings are conscious of character literals in simple one’s Quotation marks (e.g. ‘A’) and string literals in double quotes (e.g. “Hello”) is set. This has to be the case in Java. Please take care. So to define an object of the type String, one can proceed as follows:

String str = new String (“Hello”);

The objects are usually created in this way. In the case of strings, it can also be shorter:

String str = “Hello”;

Both approaches have the same meaning. Several Strings can be (as already practiced) with the help of the plus Link operators. Like here:

str = str + “World”;

In the event that str first read “Hello”, there is now in this variable the value “Hello World”. The following expression finally gives our well-known greeting on the console  out:

System.out.println (str);

String methods in java:

The String class provides many useful methods for Processing strings as shown in the below table:

Methods Description
char charAt (int index) Specifies the character at a specific position.
int compareTo (String anotherString) Compares two strings lexicographically. If both strings are the same, 0 is returned, if the string is smaller than anotherString, one value becomes smaller Returns 0, otherwise a value greater than 0.
boolean equals (Object anObject) Checks two strings for equality.
int length () Returns the number of characters.
String substring ( int beginIndex, int endIndex) Returns a substring that includes all Characters from beginIndex up to and including endIndex – 1 includes.
String toLowerCase() Converts all letters to lower case around.
String toUpperCase() Converts all letters to uppercase around.
String trim() Cuts leading and final Whitespaces (spaces, tab characters, line breaks).


The following example demonstrates the use of these methods:

The function hasSubstring checks whether the Search string is included. To this end, both will Strings first converted to lowercase letters. Play with it Upper / lower case no longer plays a role in the search. The search string also removes leading and trailing whitespaces. The Finally method returns true if the search string is in orig is included, otherwise, it returns false.

When I search tutorial in my string it gives false because there is no world tutorial in my string

java class and object

And, when I search digest it gives true because the word digest is present in the string

java class and object

From uninitialized variables and the null values:

So let’s say you declare a variable and you want to read it out.  Before initializing the variable with a value.

What is the impact?

Before we look at this in more detail, let us consider the following agree: it wouldn’t be good if our program had variables that are not initialized. That would mean, that we are using a value that just happens to be in the corresponding Storage area is to be found. We would have an uninitialized int variable, its value would be any Number. We would have an uninitialized object reference readout, this would be at any point in the memory and we would refer to the corresponding memory contents as identify our object. On top of that, a program even may not access any addresses in the memory, but only to a memory area assigned to it. So should this x-any place in memory outside of our allocated Memory area, we would also have problems with the operating system. The operating system is in one of these Don’t be squeamish. It kills our process. The program is therefore canceled. The frequent use of the subjunctive in the last paragraph allows Us can see that the Java compiler does not allow our Program to reads out non-initialized variables. See below, how he does this:

We differentiate between local variables (variables that are within a Function or a method are declared) and attributes of a Class and each considers an int variable as a representative of a value type and a rectangle object as a representative of a Reference type.

In the above code excerpt, we declare the local variables x and r and attempt to use x to initialize y, and r for initializing e.g. Both attempts fail. The compiler Reminds us that neither x nor r are initialized and refuses to translate the program. What if x and r are declared as attributes? See for yourself:

The two variables x and r are now attributes of the Test class. Again we try to read out their values ​​in method f (). In contrast to the previous program, the compiler compile this program without errors.

Attention! The explanation for this is a little more complicated:

The compiler generally does NOT know if an attribute is used before it is used was explicitly initialized. He can usually do this too do not even know! Let’s say the class has Test next to the Method f () also has a method setX (), with which the value of the Attribute x can be set – similar to setWidth () – or the setHeight () method in the Rectangle class. The compiler is active before the program can be started. He can do not know whether the setX () method is called at runtime is – and thus the x attribute is initialized – and then the method f () or whether the order is reversed.

Since the Java compiler cannot decide whether an attribute is before was initialized after reading out, it always ensures that the Attributes of an object are assigned default values ​​when it is created. This enables completely undefined memory contents to be for attributes. The default value for int variables is 0. Therefore, the above code listing the variable y is set to the value 1 (=> 0 + 1 = 1). The default value for reference types such as rectangles is zero. This is a reserved name in Java. If r is set to zero, the corresponding rectangle pointer with binary zeros is pre-occupied. This marks that r is currently set to no Rectangle instance. He then points to nothing.

In any case, the keyword zero is better than nothing and not as the numeric value 0. null is not for calculating but presses a non-existent object reference from. The following line now leads during runtime a termination of the program:

int z = r.getWidth() + 1; // NullPointerException

The attribute r thus contains the value zero. We try to work with r.getWidth() to resolve the corresponding reference, i.e. to the object to which r refers. There is a does not refer to an object, breaks the program with a so-called “data”. NullPointerException.

Our rectangular reference r becomes implicit when set to zero sets. But we can also set r explicitly to zero, independently whether it is a local variable or the attribute of a class. In the following case, we set the local variable r to zero, and then pass it method g(). If we didn’t set it to zero first, we would have it does not initialize and the compiler would return r g():

So we can use the keyword to deliberately express zero. that there is currently no corresponding instance. To conclude this course, I would like to ask you to

Please: Do not count on implicitly initialized attributes. at least not for value types. So never give the following statement if x is an attribute and not of you has been explicitly set to a certain value before:

int y = x + 1;

Here for x to assume the value 0 just because it implicitly initializes so is incredibly bad programming style. It is harmful not knowing that your compiler is in doubt for the initialization of their attributes. However, they should not exploit this. It is very irritating when variables are read out before they are set to a specific value somewhere in the source code. In addition, object-oriented programming provides that all attributes of a class are in the constructor. Follow this Paradigm always consistent, will never occur that methods can encounter implicitly initialized attributes.

Related Article:

break and continue: java break label and continue label with examples

java while loop and java do while loop with programming examples

Java for Loop Statements with Programming Examples


Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button