Thursday 26 June 2014

java creating object constructor

First of all you will have to create file with .java extension with class name same with the file name


as show in the program given



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapptwo;

/**
 *
 * @author jawadmahmood
 */
public class Student {
    private String name ;
   
    private int rollNo ;
   
   
    public void setName(String name)
    {
        this.name  = name;
    }
   
    public void setRollNo(int rollNo)
    {
        if(rollNo > 0 )
        {
            this.rollNo = rollNo;
           
        }
        else
        {
           this.rollNo = 100;
        }
    }
   
    public String getName()
    {
        return name ;
    }
   
    public int getRollNo()
    {
        return rollNo;
    }
   
   
    public Student()
    {
        name  = "not defined";
        rollNo = 500;
    }
   
    public Student(String name , int rollNo)
    {
        setName(name);
        setRollNo(rollNo);
       
    }
   
    public Student(Student s)
    {
        name = s.name;
       
        rollNo = s.rollNo;
    }
   
    public void print()
    {
        System.out.println("Student name: " + name + " ,  RollNo " + rollNo);
    }
}

as image given






and will have to create the class with main method

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapptwo;

/**
 *
 * @author jawadmahmood
 */
public class JavaAppTwo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        System.out.println("Welcom");
        
        Student s1 = new Student("ali" , 15);
        Student s2 = new Student();
        Student s3 = new Student("akhtar khan ", 55); 
        s1.print(); 
        s2.print(); 
        s3.print();
        
    }
    
}


image


now run the program 


and you will get the result as 








No comments:

Post a Comment