A brief Introduction to java classes

0
142
Fibonacci Number program in C++ using Recursion
Creating a Calculator program in Java

Classes are the blueprints used to create instances. In Java, classes acts like a container having set of data members and methods. Objects created by same class must have similar features. Java is fully associated with object oriented concepts, therefore understanding java classes is essential.
Starting with the basics, every time we code something, we need a super class that governs the whole program. The super class has a main function that controls the flow. The class name must be the same as the name of project java file i.e.

    class HelloWorld
    {
    public static main (String[] args)
    {System.out.println(“HELLO WORLD”);}
    }

Above code must be saved as “HelloWorld.java” as governing class has “HelloWorld” name. The output of this program is “HELLO WORLD”.
Easy to understand? let’s go for multiple java classes:

    governing_class {    // program class
            public static void main(String[] args) {
            parent p = new parent (); // parent class object
            child1 c1 = new child1(); // child1 class object
            child2 c2 = new child2 (); // child2 class object
            System.out.println(p.getName()); // parent calls getName
            System.out.println(c1.getName()); // child1 calls getName
            System.out.println(c2.getName()); // child2 calls getName
        }
    }
        class parent{    // parent class     
        String name = "Hey, I am Parent Class" ;
        
        public String getName()    // returns name
        {
            return name;
        }
        
    } // end parent class
     
        class child1    // child1 class
        {
            String name = "Hey, I am Child1 Class";        
            public String getName () // returns name
            {
                return name;
            }
        } // end child1 class
        
        
        class child2    // child2 class
        {
            String name = "Hey, I am Child2 Class";
            
            public String getName () // returns child2 name
            {
                return name;
            }
        } // end child2 class

This program illustrates how multiple java classes are linked with the governing class. The output is shown below. Now you know basic concepts of java classes, try it and make something interesting.o1

Fibonacci Number program in C++ using Recursion
Creating a Calculator program in Java

Leave a Reply