This is a Java Program to Create the Object for Class and to Assign Value in the Object Using Constructor.
Constructor is used to initialise the object. A constructor initializes an object immediately upon creation.
Here is the source code of the Java Program to Create the Object for Class and to Assign Value in the Object Using Constructor. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Demo
{
int a,b,c;
Demo()
{
a = 5;
b = 6;
}
void change()
{
a = 15;
b = 10;
c = a + b;
}
public static void main(String[] args)
{
Demo obj1 = new Demo();
System.out.println("a:"+obj1.a);
System.out.println("b:"+obj1.b);
obj1.change();
System.out.println("New a:"+obj1.a);
System.out.println("New b:"+obj1.b);
System.out.println("c:"+obj1.c);
}
}
Output:
$ javac Demo.java $ java Demo a:5 b:6 New a:15 New b:10 c:25
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Information Technology MCQs
- Practice Programming MCQs
- Check Programming Books
- Check Java Books
- Apply for Computer Science Internship