Class and structure in java

Java Basics: Java Class Structure Examples

Having a good understand about structure of a Java class is important to write proper, efficient and clean code. Though you can read about class declarations in the Java Language Specification (JLS), it’s quite formal and specific to language designers. So in this Java core article, I’d like to share with you easy-to-understand structure of a Java class with various real life code examples.

Table of Content:

1. Complete structure of a Java class

class className extends implements

Below is an example class that follows the above syntax. No worries if you don’t understand, as I’ll explain further below.

public class RoundedCornerSquare extends Square implements Shape < /** Field Declarations: **/ private static double cornerRadius; private String fillColor; private String borderColor; /** Static Initializers: **/ static < cornerRadius = 1.58; >/** Instance Initializers: **/ < fillColor = "White"; borderColor = "Black"; >/** Constructors: **/ public RoundedCornerSquare() < this.width = 15; >public RoundedCornerSquare(int width) < this.width = width; >public RoundedCornerSquare(int width, String fillColor) < this.width = width; this.fillColor = fillColor; >/** Method Declarations: **/ public double calculateArea() < return width * width; >public double calculatePerimeter() < return width * 4; >public void printDetails() < System.out.print("Rounded Corner Square[width=" + width); System.out.print(", radius=" + cornerRadius); System.out.print(", fillColor=" + fillColor); System.out.println(", borderColor=" + borderColor + "]"); >public static void main(String[] args) < RoundedCornerSquare square1 = new RoundedCornerSquare(); RoundedCornerSquare square2 = new RoundedCornerSquare(20, "Blue"); square1.printDetails(); square2.printDetails(); >>
public class Square < protected int width; public int getWidth() < return width; >public void setWidth(int width) < this.width = width; >>

2. Class modifiers

A class should be preceded by one or more modifiers that specify its visibility (public, protected, private, sealed) or characteristics (abstract, static, final, strictfp).

Читайте также:  Object to typescript interface online

A class can be top level class which is independent or member class which is directly inside another class (nested). The modifiers protected, private and static apply for only member classes. The modifier public can be used for any kind of classes.

A public class is accessible anywhere. The above Square and RoundedCornerSquare are examples of top-level public classes.

A private member class is accessible only within the enclosing class. For example:

public class EnclosingClass < private class MemberClass < >public void test() < MemberClass m = new MemberClass(); >>

A protected member class is accessible in the enclosing class and different classes in the same package. Below is an example:

public class EnclosingClass < protected class MemberClass < >>

An abstract class means that it is incomplete with abstract methods that has no body (no concrete code). And non-abstract subclasses must provide implementation for the abstract methods. Below is an example:

public abstract class Animal < public void eat() < System.out.println("Eating.."); >public abstract void move(); > public class Bird extends Animal < public void move() < System.out.println("Flying. "); >>

A final class cannot be extended. Check this article to learn more about final class.

And read this article to understand about using strictfp modifier.

Recent Java versions allow you to declare a sealed class which specifies exactly its known subtypes. For example:

public sealed class Shape permits Rectangle, Circle, Triangle

Here, the Shape class permits exactly only 3 subclasses that are Rectangle , Circle and Triangle . These subclasses are known at compile time, and no other classes can extend the Shape class.

3. Class name

The name of a class should follow general naming for identifiers in Java. It should start with an upper case letter. It should not contain special characters ($, _, -, @. ). If class name is compound words, the first letter of each word should be capitalized (camel case naming).

You should spend time to name a class in way that it is descriptive and meaningful — the name reveals the intention/purpose of the class properly. It should not an ambiguous name.

Some examples of bad class names: 1StudentManager , square2 , Paint_Canvas , applicationcontext ,…

Some examples of good class names: StudentManager , Square , PaintCanvas , ApplicationContext .

4. Extending a super class

A class can inherit public and protected members from another class via the extends keyword. In the above example, the RoundedCornerSquare class extends the Square class:

public class RoundedCornerSquare extends Square < >public class Square < protected int width; public int getWidth() < return width; >public void setWidth(int width) < this.width = width; >>

This means RoundedCornerSquare is a subtype of Square and it inherits the member variable width and methods getWidth() and setWidth() .

Note that a class can extend only one direct superclass. Read this article to learn more about inheritance in Java.

5. Implementing super interfaces

A class can be a subtype of one or more interfaces via the implements keyword. In the precede code example, you can see the RoundedCornerSquare class implements the Shape interface:

public class RoundedCornerSquare extends Square implements Shape
public class SUV extends Car implements Vehicle, Moveable

The class SUV implements two interfaces Vehicle and Moveable so it must override methods declared in those interfaces.

6. Field Declarations

In Object-Oriented Programming (OOP), fields represent characteristics of a class. You declare fields or member variables at the beginning of the class’ body. As you can see in the above code example:

public class RoundedCornerSquare extends Square implements Shape

Here, this class has 3 fields. The first one is a static field ( cornerRadius ) and the last twos are instance fields. Read my explanation in this article to understand static vs. non-static stuffs in Java.

You can declare any number of fields in a class and in any order. However, it’s a good practice to declare fields at the beginning of the class for readability.

7. Static Initializers

If you want a piece of code to be executed only once when the class is first loaded, regardless the number of instances of the class created, you can use static initializers. As you can see in the above example, the RoundedCornerSquare class has one static initializer (the code inside static < >block):

public class RoundedCornerSquare extends Square implements Shape < private static double cornerRadius; static < cornerRadius = 1.58; >>

In a Java class, you can put any number of static initializers and they are executed in the order specified in the class. Learn more: Java default Initialization of Instance Variables and Initialization Blocks

8. Instance Initializers

If you want a piece of code to be executed whenever a new instance of a class is created, you can use instance initializers. Below is an example:

public class RoundedCornerSquare < private String fillColor; private String borderColor; < fillColor = "White"; borderColor = "Black"; >>

An instance initializer is the code between < >block. You can put any number of instance initializers in a class, and they are executed in the order they appear in the class.

Read this article to learn more about initialization blocks.

9. Constructors

The next part in a Java class is constructors. A constructor is a special method that is executed when a new object (instance) of the class is created using that constructor (it has same name as the class name). Let’s see an example:

public class RoundedCornerSquare extends Square implements Shape < private static double cornerRadius; private String fillColor; private String borderColor; public RoundedCornerSquare() < this.width = 15; >public RoundedCornerSquare(int width) < this.width = width; >public RoundedCornerSquare(int width, String fillColor) < this.width = width; this.fillColor = fillColor; >>

10. Method Declarations

After constructors, you declare methods. A method implements a specific behavior of a class. In the precede example, the RoundedCornerSquare class implements 4 methods:

public class RoundedCornerSquare extends Square implements Shape < public double calculateArea() < return width * width; >public double calculatePerimeter() < return width * 4; >public void printDetails() < System.out.print("Rounded Corner Square[width=" + width); System.out.print(", radius=" + cornerRadius); System.out.print(", fillColor=" + fillColor); System.out.println(", borderColor=" + borderColor + "]"); >public static void main(String[] args) < RoundedCornerSquare square1 = new RoundedCornerSquare(); RoundedCornerSquare square2 = new RoundedCornerSquare(20, "Blue"); square1.printDetails(); square2.printDetails(); >>

A method can be static or non-static. You can declare any number of methods in any order in the class. However, it’s a good practice to keep the number of methods and the method body as small as possible.

So far, you have learned details about structure of a Java class with code examples. I recommend you read the following articles to learn more.

Watch the following video to see the coding in action:

Further Reading:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Last Minute Java Class Structure or Syntax Overview Tutorial

Java Class Object Infographic Explanation

A Java program consists of a CLASS with some Code and Data. Code is also called Method(s). Data is also called Variable(s). Java is an Object-Oriented Language. Let us know more about Java Class Structure and Syntax in this Last Minute Tutorial.

Java Class Structure and Syntax Overview

A Java Class is like a wrapper or envelope that comprises a number of Methods and Variables. In C language, these methods are called Functions . A Java class is like a Blue-Print or Specification-Sheet or Prototype that defines how an Object instantiated out of it (class) to behave and store data.

Parts of a Java Class

A Java Class broadly consists of the following.

Java Class Syntax

Rules For Creating a Class:

  • Each class should contain an Opening Brace » Closing Brace «>».
  • Each method has its own Opening and Closing Braces.
  • Each Java class uses the keyword «class» followed by a valid CLASSNAME.
  • CLASSNAME or simply «Name» can be any valid identifier.
  • CLASSNAME can start with only a Character Alphabet, Underscore (_) or a Dollar ($) sign.
  • CLASSNAME can not start with a number or digit. But, numbers may come in the middle or end of the NAME.
  • Except Underscore and Dollar, no other special symbols are allowed to be part of an Identifier.
  • In a .java file, there can only be one » public class «. Other classes may be defined without specifying «public» access specifier.
  • There is no restriction on the number of methods present in a class.
  • A Java method may or may not return a typed-value.
  • A Java method can be public, private, protected or default.
  • A Java variable can be public, private, protected or default.
  • The MAIN method is not necessary. It is used only to control the project program flow from the start to exit.
  • Some projects or frameworks do not allow adding a «main» method to the Java program.
  • Some complex Java classes contain «implements» or «extends» keywords next to the CLASSNAME followed by predefined Class-Names. This is part of Inheritance.

Creating a Java Class Object and Using it

A Java object is like a variable of a particular data-type. Here the Object is of the CLASS-type we define. A Class is of no use unless we create Objects. All objects are created at run-time dynamically. Creating an object involves allocating memory to it and returning a reference or handle of the memory location. We create Java objects using a » new » keyword.

A Java Class exists only theoretically or virtually. But an object exists really in memory. A class is comparable to a Structure in a C programming language.

Java Class Object Explanation

In the above Infographic, we tried to explain what really an Object is. Here, Cupcake Pan is like a prototype. Assume, it has only one mould. It defines what should be the shape of a final Object. Using methods like Kneading, we turned Variables like Ingredients into useful Cupcakes or Objects. Remember that each Object is unique and has its own properties.

An example Java Class is given below. A House object «obj» is created using the «new» keyword. The keyword «new» tells the Java Runtime to allocate some memory to the House object and return a reference to «obj«. Now, the object can be accessed using the reference obj.

Each House object has two properties or variables namely width and height. Method getArea() calculates are of the House object and returns it.

public class House < int width, height; int getArea() < return width*height; >public static void main(String[] args) < House obj = new House(); obj.width = 10; obj.height= 20; int area = obj.getArea(); System.out.println("Area of the house orangecode2 font24">Share this Last Minute Java Classes and Objects Tutorial with your friends and colleagues to encourage authors.

Источник

Оцените статью