Java class structure and class declaration

Structure of the Java class

A class is a template that creates an object, and a Java program is just a collection of these classes.

In Java, a class consists of two elements, each of which is shown below.

First, the data attributes that an object can have include the data itself.

Second, methods can manipulate data.

The code structure of the Java class is shown below.

class ClassName { //Class header area

	//Member variable
	type1 varName1 = value1;
	typeN varNameN = valueN;

	//Constructor
	ClassName(args1) {
		//Write the initialization process of the generated object
	}
	ClassName(argsN) {
		...
	}

	//Method
	mtype mName1(margs1) {
		//Writing methods
	}
	mtype mNameN(margsN) {
		...
	}

}
class SampleClass {
	int a;
	int b;
	int c;

	//constructor. Name is the same as class name
	public SampleClass(int x, int y, int z) {
		a= x;
		b=y;
		c=z;
	}

	// Method
	public int sum() {
		int d;
		d = a + b + c;
		return d;
	}
}
Java class basic example

Java class declaration

When you create a class in Java, you use a qualifier that specifies the nature of the class.

[public/final/abstract] class ClassName {  //Class header
	... //Class Members
}

In the code above, the qualifiers are public, final, abstract, etc. Each qualifier has the following characteristics.

  • public: This class can be used by other classes. That is, all classes can create objects of the class specified by this qualifier.
  • final: A class that can not have subclasses.
  • abstract: An abstract class with abstract methods. An abstract method is a bodyless method that describes the actual function.

If you do not specify qualifiers such as public, final, and abstract, you can only access classes in the same package.

//Only the attributes of the data
public class Box {
	int width;
	int height;
	int depth;
}
Class declaration example 1
//Classes with properties and methods of data
public class Box {
	int width;
	int height;
	int depth;
	public void volume() { //Method
		int vol;
		vol = width * height * depth;
		System.out.println("volumn is" + vol);
	}
}
Class declaration example 2
//Classes with properties, constructors, and methods of data
class Box {
	int width;
	int height;
	int depth;
	public void Box(int w, int h, int d) {
		width = w;
		height = h;
		depth = d;
	}

	public void volume() {
		int vol;
		vol = width * height * depth;
		System.out.println("Volume is " + vol);
	}
}
Class declaration example 3

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post