Constructors in Java

Constructors in Java:

We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it.

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

In Student.java class we define the objects and methods. We call these objects and methods in Main.java class as shown below.

Student.java class:

student class java
public class Student {
	
	String stu_name;
	int stu_age;
	double stu_marks;
	
	Student (String stu_name, int stu_age, double stu_marks){
		
		this.stu_name = stu_name;
		this.stu_age = stu_age;
		this.stu_marks = stu_marks;
	}
	
	void ranking() {
		
		System.out.println(this.stu_name + " is the topper");
	}
	
	void age() {
		
		System.out.println("Ronald is " + this.stu_age + " years old");
	}
	

}

Main.java Class:

java constructor class example
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Student student1 = new Student("Andrew",22, 80.90);
		Student student2 = new Student("Ronald",22, 91.20);
		
		System.out.println(student1.stu_name);
		System.out.println(student1.stu_age);
		System.out.println(student1.stu_marks);
		
		System.out.println();
		
		System.out.println(student2.stu_name);
		System.out.println(student2.stu_age);
		System.out.println(student2.stu_marks);
		
		System.out.println();
		
		student1.ranking();
		student2.age();
		
		
	}

}

Tutorial MySQL
Tutorial Python
Tokens in C++
Database Management System (DBMS)
Applications of Computer
Basic Components of Computer System
Java (programming language)– Wikipedia

Comments (No)

Leave a Reply