Java Class_Object_Constructor
Java Class_Object_Constructor
// Student class
class Student {
// Attributes
String name;
int age;
// Constructor
Student(String n, int a) {
name = n;
age = a;
}
// Main class
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
Student s2 = new Student("Bob", 22);
s1.display();
s2.display();
}
}
4. Class with Getter and Setter Methods
// Person class
class Person {
private String name;
// Setter method
void setName(String n) {
name = n;
}
// Getter method
String getName() {
return name;
}
}
// Main class
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("John");
System.out.println("Person's name: " + p.getName());
}
}
5. Java program with class A having a default constructor,
instance variables (int a, String name), and a method
show() that prints the values. Class B contains the main
method.
class A {
// Instance variables
int a;
String name;
// Default constructor
A() {
a = 10; // Default value for 'a'
name = "John"; // Default value for 'name'
}
// Method to display values
void show() {
System.out.println("Value of a: " + a);
System.out.println("Name: " + name);
}
}
// Class B (Main class)
public class B {
public static void main(String[] args) {
// Creating an object of A
A obj = new A();
// Calling show() method
obj.show();
}
}
6. program without a default constructor. Since Java
provides default values for instance variables (int → 0,
String → null), we don’t need to explicitly initialize them.
class A {
// Instance variables (initialized by default)
int a; // Default value: 0
String name; // Default value: null
class A {
int a; String name; // Instance variables
// Parameterized constructor
A(int x, String y) {
a = x; name = y;
}
// Copy constructor
A(A obj) {
a = obj.a; name = obj.name;
}
// Method to display values
void show() {
System.out.println("Value of a: " + a);
System.out.println("Name: " + name);
}
}
public class B {
public static void main(String[] args) {
// Creating an object using the parameterized constructor
A obj1 = new A(10, "Alice");
// Creating a copy of obj1 using the copy constructor
A obj2 = new A(obj1); // Displaying values of both objects
System.out.println("Original Object:");
obj1.show();
System.out.println("\nCopied Object:");
obj2.show();
}
}
9. private constructor
// Private constructor
private A() {
a = 10;
b = 58.52;
c = "Amit";
// Default Constructor
A() {
a = 100;
b = 53.55;
c = "Amit";
}