Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Class And Object

Class is the core concept of java, because a java program is nothing but a class. So we will know about class in detail. Let's move forward.

  • 1. In general a class is defined as grouping of objects having identical properties, common behavior and shared some relationship to perform a specified task.
  • 2. For example a computer system, a car etc.
  • 3. According to JAVA point of view a class is a non-primitive(user-defined) data type, which fully defines an object
  • 4. That means without a class, we can't declare an object. Overall an object is identified by a class.
  • 5. A class contains data or method or data and method which is considered as property of that class.
  • 6. Once we create a class, we can declare any no. of objects belonging to that class.
  • 7. An object is a named dynamic memory area which contains the property of class. We allocate this memory using new operator. The general form of an object is: new classname();

How to declare a class:

Class classname
{
	field declaration;
	Method declaration;
}

Example

class MyClass
{
	int x,y;
	void get();
	void show();
}

Here in the above source code, the keyword class tells to the compiler that there is a class named as MyClass taking two int data members such as x and y and two methods such as get( ) and show( ) respectively.

See an example MyClass1.java;

class MyClass1
{
	int x=100;
	public static void main(String[] args)
	{
		MyClass1 obj=new MyClass1();
		System.out.println(obj.x);
	}
}

Output: 100


Multiple objects:

We can create multiple objects of one class. For example;

MyClass2.java
class MyClass2
{
	int x=100;

	public static void main(String[] args)
   	{
		MyClass2 ob1=new MyClass2();
		MyClass2 ob2=new MyClass2();
		System.out.println(ob1.x);
		System.out.println(ob2.x);
   	}
}

Output:
100


Using multiple classes:

AreaTriangle.java

class Area {
	double base, height;
	void get() {
		base = 5.2;
		height = 4.6;
	}
	void show() {
		double a;
		a = 0.5 * base * height;
		System.out.println("area is" + a);
	}

}
class AreaTriangle

{
	public static void main(String[] args) {
		Area obj = new Area();
		obj.get();
		obj.show();
	}
}

Output:

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext