Powered by Blogger.

Java - Write a Java program to create a class named ArrayExample, in this class declare an array named myArray of Car type. Now initialize the myAarray and call the display method for each index of myArray in the main method. In the Car class there are two class variables: carName and carModel, constructor (initialized the variables), and display method

Question ## Write a Java program to create a class named ArrayExample, in this class declare an array named myArray of Car type. Now initialize the myAarray and call the display method for each index of myArray in the main method. In the Car class there are two class variables: carName and carModel, constructor (initialized the variables), and display method?

A class is a software blueprint. A class defines the set of data elements (called attributes), as well as the set of behaviors or functions (called methods). Together, attributes and methods are called members of a class. In Java technology, class name usually starts with a capital letter, attribute and method name usually starts with a small letter. The access modifier for the classes in the Java technology can be public or default. The Java technology class, attribute, constructor, and method declaration takes the following forms:

Syntax: 

<modi f i e r > c l a s s <clas s name>{
<modi f i e r > <data type> <at t r ibut e name >;
<modi f i e r > <data type> <at t r ibut e name>[=<value >] ;
[<modi f i e r >] <clas s name>(<argument> ){
<statement>
}
<modi f i e r > <r e turn type > <method name>(<argument> ){
<statement>
}
}

A constructor is a set of instructions designed to initialize an instance or object. The name of the constructor must always be the same as the class name. Constructor do not return any value. Valid modifiers for constructors are public, protected, and private.

Program Solution:

class Car{
 public String carName;
 public String carModel;
 public Car(String carName,String carModel){
 this.carName = carName;
 this.carModel = carModel;
 }
 public void display(){
 System.out.println(”Name:”+carName+”,and Model:”+carModel);
  }
 }   // end of Car class;
  public class ArrayExample{
 public static void main(String[]args){
 Car[]myArray = new Car[3];
 myArray[0] = new Car(”BMW”,”Road Track 509”);
 myArray[1] = new Car(”Toyota”,”X corola 2012”);
 myArray[2] = new Car(”Honda”,”M 2012”);
 for(int i=0; i<3; i++)
 {
 myArray[i].display();
   }   // end of for loop;
  }   // end of the main method();
 }   // end of the class;

0 comments:

Post a Comment