how to create an object in java code example
Example 1: java create new object
Car mycar = new Car();
Example 2: make an object in java
public class Puppy {
public Puppy(String name) {
System.out.println("Passed Name is :" + name );
}
public static void main(String []args) {
Puppy myPuppy = new Puppy( "tommy" );
}
}
Example 3: using class in java
public class HelloWorld {
public static void main(String[] args) {
class Number{
int number;
public boolean isPos(){
if(number > 0){
return true;
} else {
return false;
}
}
}
Number myNumber = new Number();
myNumber.number = 7;
if(myNumber.isPos()){
System.out.println(myNumber.number + " is positive!!!");
} else {
System.out.println(myNumber.number + " is not positive!!!");
}
}
}
Example 4: object in java
Objects: came from class, we can create multiple objects from a class
ArrayList<> list = new ArrayList<>();
Class refName OBJECT
each object has its own copy of instance variable
· declared outside the blocks or methods
Object: Instance of the class. We can store different data's to objects
Object Creation: with new keyword.
ClassName obj = new ExistingConstructor;
Example 5: create object and call method in java
MyClass **insert_name** = new MyClass();
insert_name.**method_name**();