Choose Your Language

Friday, 5 December 2014

How to access the private member of a class in another class?

public class MyMainClass{
   
    public static void main(String args[])
    {
    MySubClass mySubClass=new MySubClass();
    System.out.println(mySubClass.getPrivateMethod());
    }
    }

class MySubClass {         
           
         private String myPrivateMethod(){
         return "Aravind Sankaran";
         }
        
         public String getPrivateMethod(){
             return myPrivateMethod();
         }
    }

Output:
Aravind Sankaran

Wednesday, 3 December 2014

How to access non-static member of a class using it's static method

package com.test.java;

public class Pen {
    String name="Aravind";//non static member
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub       
        displayName();
    }

    static void displayName(){
        Pen p=new Pen();
        System.out.println(p.name);
    }
}

Output:
Aravind