Skip to content

Commit

Permalink
Constructor and this use in java
Browse files Browse the repository at this point in the history
  • Loading branch information
suhanigupta23 authored Feb 20, 2024
1 parent 6e4af16 commit c8777d0
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions constructors_and_this_use_sample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//THIS IS A SAMPLE OF USING CONSTRUCTOR INT JAVA BOTH DEFAULT AND THE PARAMTERISED CONSTRUCTOR


import java.util.*;
public class Program
{
public static class Person
{
int age;
String name;
void saysHi()
{
System.out.println(name+" ["+age+"] says hi");
}
//default constructor
Person()
{

}
//BOTH THE PARAMETRISED AND DEFAULT CONSTRUCTOR ARE NEEDED IF WE WRITE THE PARAMETRISED CONSTRUCTOR.
//parameterised constructor
Person(int age,String name)
{
this.name=name;
this.age=age;
//this. used for the calling the heap constructed in the stack when we below wrtie the new Person
}
}
public static void main(String[] args)
{

Person p1=new Person();
p1.age=19;
p1.name="Jiya";
p1.saysHi();

Person p2=new Person(20,"Nishi");
p2.saysHi();


}
}

0 comments on commit c8777d0

Please sign in to comment.