Accessing private class methods

This program works, but I am having some problem grasping the concept. If class Room can access methods in class House using gethWidth() and getHeight(), why is it that class Type cannot access those same
methods. Instead, it can only access setWidth() and
setHeight()?
class House {
private double width;//width of room
private double length;//length of the room
double getWidth() {return width;}
double getLength() {return length;}
void setWidth(double w) {width=w;}
void setLength(double l) {length=l;}
void showdim() {
System.out.println("My townhouse has two bedrooms.");
class Room extends House {
String bedroom;
double area() {
return getWidth() * getLength();
void showBedroom() {
System.out.println("The biggest room is the" + " " + bedroom + ".");
class Type {
public static void main(String args[]) {
Room r1=new Room();
Room r2=new Room();
r1.setWidth(14.5);
r1.setLength(20.6);
r1.bedroom="master bedroom";
r2.setWidth(15.2);
r2.setLength(15.3);
r2.bedroom="Guest Room";
System.out.println();
r1.showdim();
r1.showBedroom();
System.out.println();
System.out.println("The area of the" + " " + r1.bedroom+ " " +
"equals"+ " "+ r1.area()+ " " + "square feet.");
}

Thanks to all. But the comments provided so far does not answer my question. Over the past few days I have struggled over the question and I think I found the answer. Others are welcome to comment.
Initially, "width" and "length" were decleared as private in class "House". For other classes to gain access, they had to use "accessor methods". Two accessor methods were decleared: "getWidth" and "getHeight"; and "setWidth" and "setLength". The first two methods "return"; the last two were "void". In class Room, I set up a method to return the calculation, so I used "getWidth and "getLength". In class "Type" I had to use the other method "setWidth", since I was declearing the actual values. Makes sense?

Similar Messages

  • Please Help!!! Problems access other classes methods

    I am having a problem accessing another classes methods varibles. I have tried a number of ways but with no success. Here is my problem:
    I have the main(), from there it's calls the class GetVar(), GetVar stores info in Class HousingForVar(), and finially, I have a class TryinToTalkToHousing() that I use to access HousingForVar()'s methods. I know I can use the keyword new but if I do that then it erases over the data I put in. Please can anyone help, this has been driving me nutz all day. Thank you in advance.
    Roman03
    ***EACH CLASS IS A DIFFERENT FILE****
    public class TestMain
         public static void main( String args[] )
              GetVar getVarible = new GetVar();
              getVarible.heroF();
    import java.util.Scanner;
    public class GetVar
         public void heroF()
              String someEntered;
              Scanner input = new Scanner( System.in);
              System.out.println("Enter a string: ");
              someEntered = input.next();
              HousingForVar houseForData = new HousingForVar(someEntered);
              System.out.printf("Retieved from Class GetVar, you entered: %s\n", houseForData.getCollectVar() );
    import java.util.Scanner;
    public class HousingForVar
         private String getData;
         public HousingForVar(String enterInfo)
              getData = enterInfo;
         public void setGetVar(String enterInfo)
              getData = enterInfo;
         public String getCollectVar()
              return getData;
    import java.util.Scanner;
    public class TryinToTalkToHousing
         public void someMeth()
              String getInfoFromHousing;          
              System.out.printf("Started out at TryinToTalkToHousing Class\n Retieved from Class GetVar from %s\n",
              houseForData.getCollectVar() );
    \* I know this doesn't work, but if I make a new object of the class HousingForVar it's going to write over my input, so what do I do? I am still learning, Please help*\

    I don't use 1.5, so you'll have to convert it back, but see if you can follow the flow of this
    import java.io.*;
    class TestMain
      GetVar getVarible;
      public TestMain()
        getVarible = new GetVar();
        getVarible.heroF();
        System.out.println("******");
        new TryinToTalkToHousing(this).someMeth();
      public static void main(String[] args){new TestMain();}
    class GetVar
      HousingForVar houseForData;
      public void heroF()
        try
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          System.out.print("Enter a string: ");
          String someEntered = br.readLine();
          houseForData = new HousingForVar(someEntered);
          System.out.println("Retieved from Class GetVar, you entered: "+houseForData.getCollectVar()+"\n");
        catch(Exception e){e.printStackTrace();}
    class HousingForVar
      private String getData;
      public HousingForVar(String enterInfo)
        getData = enterInfo;
      public void setGetVar(String enterInfo)
        getData = enterInfo;
      public String getCollectVar()
        return getData;
    class TryinToTalkToHousing
      TestMain parent;
      public TryinToTalkToHousing(TestMain t){parent = t;}
      public void someMeth()
        System.out.println("Started out at TryinToTalkToHousing Class\n"+
        "Retieved from Class GetVar, you entered: "+parent.getVarible.houseForData.getCollectVar()+"\n");
    }

  • Accessing Private class data

    Hi I have Created Class in SE24 and I have declared three public methods in that class and Finally I made Class as Private. then How can access the public methods of the class From the Report Program.
    Regards,
    D.Kiran Kumar.

    >
    Gaurav Khare wrote:
    > hi Kiran,
    >
    > you can not access the public methods of the private class because you can not create the object of that private class......
    >
    > Thanks and Regards
    > Gaurav Khare
    Not so. Consider a class my_class which is marked as private. Create a static public method, which returns r_myinstance TYPE REF TO my_class. The body of the static public method is
    CREATE OBJECT r_myclass
    . The static method is called a factory method. It can be used to implement the singleton pattern, and in other ways. There is extensive literature about this on the net.
    matt

  • Accessing Super Class methods

    Hi,
    If I have a Subclass that overrides a method in a superclass, is it possible to call that method from the superclass?
    Thanks

    Hi thanks for the reply, but that works for static methods, I'm trying to figure out non-static methods. Below, I want to call the method a() from the superclass using an instance of the subclass.
    class superclassA
    void a()
    System.out.println("in method a");
    class subclassA extends superclassA
    void a()
    System.out.println("in method b");
    public class overtest
    public static void main(String [] args)
    subclassA sub = new subclassA();
    superclassA.a();//non-static method a cannot be referenced from a static context
    Thanks!

  • Javadoc for private classes methods

    I know the Javadoc tool is primarily used for documenting a public API.
    Is it considered bad style ever to use it for internal documentation.... description of what private methods are for, why they were selected, etc. It seems like that could be useful too.
    Thanks for any thoughts,
    John

    Hi,
    As stated above, javadoc will not be generated for private methods if you don't use that switch. But that's not what I want to say...
    javadoc should be used to document what a method does, and the expected arguments etc. It should not say how it solves it's problem (with a few exceptions, e.g. a sorting algorithm can state if it is stable or not, and best/wors case scenarios and execution times).
    So I have adopted to some thins I saw a very long time ago, but I can't remember where. I usually document code in the following format.
    * Javadoc
    * Documentation of the method, arguments, etc.
    /* Impl note:
    * A note about how the method is implemented / a short note
    * about things one have to think about etc.
    public void method() {
    }So I use both javadoc and implementation comments. (But implementation comments are only used if a method is complex or hard to understand)
    /Kaj

  • Reflection problem with private class

    I am trying to write a junit on private class and I am stuck not knowing how to access private class.
    Here is the structure of my code:
    public abstract class cars extends auto{
    private class model{
    String name;
    String year;
    String make;
    private model getInfo(name, year, make{
    Model mod = new Model();
    mod.name = "Echo";
    mod.year = "1992";
    mod.make = "Toyota";
    return mod;
    }Basically how do I use reflection so I can write assert such as
    assertEquals(getInfo.year, "1992");Thanks in advance!

    You don't. Private methods, members, and classes are considered implementation details and should not be directly tested with your unit tests.

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Accessing private method of a class from report

    Hello All,
    I would have to access a private method of a class from a report.
    Is it possible to access private mehod otherthan from its own class and friend classes.
    Please guide on this. If is possible, to access please give some sample code.
    Thanks & Regards,
    Vishnu Priya

    Hi,
    By using the friend concept you can access private attribute or method in outside class.
    Try the following code,
    CLASS C1 DEFINITION DEFERRED.
    CLASS C2 DEFINITION CREATE PRIVATE FRIENDS C1 .
    PRIVATE SECTION.
    DATA : NUM TYPE I VALUE 5.
    METHODS : M2.
    ENDCLASS.
    CLASS C2 IMPLEMENTATION.
    METHOD M2.
    WRITE:/5 'I am method m2 in C2'.
    ENDMETHOD.
    ENDCLASS .
    class c1 definition.
    public section .
    methods : m1.
    endclass.
    class c1 implementation.
    method m1.
    DATA : OREF2 TYPE REF TO C2.
    CREATE OBJECT OREF2.
    WRITE:/5 OREF2->NUM.
    CALL METHOD OREF2->M2.
    ENDMETHOD.
    endclass.
    START-OF-SELECTION.
    DATA : OREF1 TYPE REF TO C1.
    CREATE OBJECT OREF1.
    CALL METHOD OREF1->M1.
    Regards,
    Jeyakumar.A
    Edited by: Jeyakumar Aasai on Apr 14, 2011 11:51 AM

  • How to ivoke a method on an object of a private class

    When I did it I got a java.lang.IllegalAccessException.

    Well 'private' does have a well-known meaning in
    Java, and it's been working in Java for at least 11
    years. Surely you knew that?The combination "private class" seemed unusual
    and made me de-focus from the rest of it.
    Re your example, special rules apply to inner
    classes. The access modifiers aren't tested by the
    enclosing class.Yes. The only way I am aware of of having a "private class" (as the subject implies) is to have a nested class.
    I agree one would be able to access methods on an instance of such a class only from the embedding class (or peer nested classes).

  • How to access a proctected method of a class

    Hi All,
    I have the below code where in the idents_get is a protected method of the class.so when i activate it is throwing an error, method is unkown or protected or private.
    data: gv_class TYPE REF TO /tdag/cpcl_decl_sub_view_ctrl.
       create object gv_class.
        CALL METHOD gv_class->idents_get
          EXPORTING
            i_estcat       = gc_estcat6
            i_pos_wanted   = 1
          IMPORTING
            et_idents      = lt_idents
          changing
            xt_recns       = li_recn
          EXCEPTIONS
            read_failed    = 1
            others         = 2.
    i know protected methods can be accessed in derived class.
    I'm new to ABAP oops concepts please give me some pointers to access a protected method.
    or any sample code to access protected method.
    Thanks in advance,
    Srilakshmi.

    Hello Srilakshmi
    You can access protected methods WITHIN an instance of the class or WITHIN an instance of a sub-class.
    However, in your case you are calling the method from the report and, therefore, the class must be PUBLIC.
    Regards
      Uwe

  • Need to restrict base classes method to be accessed by child class object

    class Sample
    public void setValue(String sval)
    System.out.println("sValue is : "+sval);
    class ChildClass extends Sample
    public void fnsetValue(String sval)
    super.setValue(sval);
    class check
    public static void main(String arg[])
    ChildClass chld=new ChildClass();
    chld.fnsetValue("pavan");
    chld.setValue("pavan");
    Note : {color:#ff0000}Kindly don't change the access specifiers.{color}
    I need that the "setValue" method should not be accessed by "ChildClass" object.
    Thanks u

    hi
    Thank u for replying and I have solved the issue in the following manner
    class Sample
         public void setValue(String sval)
              System.out.println("sValue is : "+sval);
    class ChildClass
         InnerClass iclass;
         private Childclass()
              iclass = new InnerClass();
         public static ChildClass getIstance()
              new ChildClass();
         public void fnsetValue(String sval)
              iclass.setValue(sval);
         private class InnerClass extends Sample
              public Innerclass()
                   super();
    class check
         public static void main(String arg[])
              ChildClass chld=chld.getIstance()
              chld.fnsetValue("pavan");
              chld.setValue("pavan"); //No this not visible mark the statement comment
    }

  • Accessing private attribute of a class from its Friend Class

    Hi Experts ,
    Please help me to understand how can i access private attribute of one class from its friend class.
    I am coding in Method (DO_SAVE) of class /BOBF/CL_TRA_TRANSACTION_MGR.
    I need to access private variable ( MO_BOPF) of class /BOBF/CL_TRA_SERVICE_MGR ( Friend of /BOBF/CL_TRA_TRANSACTION_MGR ).
    Regards,
    Reny Richard

    Hi Reny,
    You should be able to access by creating object of friend class.
    Sample:
    data lo_frnd     TYPE REF TO  /BOBF/CL_TRA_SERVICE_MGR.
    data lo_compl  type REF TO /BOBF/IF_TRA_TRANS_MGR_COMPL.
       create OBJECT lo_frnd
         exporting
                   iv_bo_key = '111'
                   IO_COMPL_TRANSACTION_MANAGER = lo_compl.
    "access the private object of friend class
       clear lo_frnd->MO_BOPF.
    Note: need to provide iv_bo_key & IO_COMPL_TRANSACTION_MANAGER while creating object.
    Hope this helps you.
    Regards,
    Rama

  • How to access private attribute of a class from its Friend Class

    Hi Experts ,
    I am coding in Method (DO_SAVE) of class /BOBF/CL_TRA_TRANSACTION_MGR.
    I need to access private variable ( MO_BOPF) of class /BOBF/CL_TRA_SERVICE_MGR ( Friend of /BOBF/CL_TRA_TRANSACTION_MGR ).
    Please help me to understand how can i access private attribute of one class from its friend class.
    Regards- Abhishek

    Hi Reny,
    You should be able to access by creating object of friend class.
    Sample:
    data lo_frnd     TYPE REF TO  /BOBF/CL_TRA_SERVICE_MGR.
    data lo_compl  type REF TO /BOBF/IF_TRA_TRANS_MGR_COMPL.
       create OBJECT lo_frnd
         exporting
                   iv_bo_key = '111'
                   IO_COMPL_TRANSACTION_MANAGER = lo_compl.
    "access the private object of friend class
       clear lo_frnd->MO_BOPF.
    Note: need to provide iv_bo_key & IO_COMPL_TRANSACTION_MANAGER while creating object.
    Hope this helps you.
    Regards,
    Rama

  • Access of undefined method/property through reference with a static type Class

    I get the following error: (it's not word for word but you get the idea)
    Error: Access of undefined method getStatus through reference with a static type Class.
    Here's what's happening in the code. I'm trying to create a User class that is instantiated at the start of my app. I want the User class to have properties like mainStatus, with helper methods like setStatus etc. Pretty simple.
    so on my HardDisk I have my flash_working folder with all my flash projects. I created my class file/package under the directory com.mypackage
    package com.mypackage
        import flash.display.*;
        public class User extends Sprite
            public var mainStatus:int;
            public function User()
                trace("User Created!");
                mainStatus = 0;
            public function setStatus(status:int):void
             mainStatus = status;
        public function getStatus():int
            return mainStatus;
    Ok, so far so good.
    now I created a new .fla file under the root of /flash_working/. The class file is in /com/mypackage/User.as
    in my .fla file I have:
    import com.mypackage.User;
    var myUser:User = new User();
    var i = User.getStatus();
    trace(i);
    That's all the code I have. Could someone please explain why it's giving me that error?
    If I try to access the public var mainStatus through user.mainStatus that gives a similar error saying:
    Error: Access of undefined property mainStatus through reference with a static type Class.
    Thanks for any help!
    jef3189

    the public getStatus() function that you created needs to be referred to through an instance of the class.
    So:
    import com.mypackage.User;
    var myUser:User = new User();
    var i = myUser.getStatus();
    trace(i);
    Also, an aside. You can create a getter/setter for status, to avoid having to do the function as such.
    package com.mypackage
        import flash.display.*;
        public class User extends Sprite
            public var mainStatus:int;
            public function get status():int
                return mainStatus;
            public function set status(value:int):void
                 mainStatus = value as int;
              public function User()
                trace("User Created!");
                mainStatus = 0;
    And then, you can call it as:
    import com.mypackage.User;
    var myUser:User = new User();
    trace(myUser.status);
    EDIT
    I just noticed that you made the variable public as well, which means you can access it without getter/setter or function.
    import com.mypackage.User;
    var myUser:User = new User();
    trace(myUser.mainStatus);

  • Accessing java class and methods within JSP

    Hi All,
    I am writing a JSP page, and need to instantiate an object of a certain class within my package, in my JSP page.
    How do I do that? Do i use the <%import = "Whatever.class" %>
    Any help would be greatly appreciated.
    Kal.

    Hi.. Thanks for ur reply.
    I am actually having a problem with the import statement. So the part where you have mypackage.Myclass, it is not working for me.
    I am using Sun Forte.. and the directory is myprojects/test/Classes/MyClass.java
    so how would the import statement look like?
    Thanks
    Kal.
    Using directive for import statements:
    <%@ page
    import="java.util.*,java.sql.*,mypackage.MyClass" %>
    Then use scriptlet:
    <%! MyClass c= new MyClass(); %>
    <%! private void method() {...} %>
    <%= c.getxxx() %>
    ...and so on

Maybe you are looking for

  • PSE 7 Green Eyes

    I obtained a trial version of PSE 7.0 to try to correct green eyes in photos of our Westies. The Photoshop web site says the red-eye fix in Quick Fix also removes green and white eyes for animals. I tried it on three photos, and it does not. I also t

  • Best Way to Handle Buttons

    I have a complex button graphic that I use for all the buttons in my Flash project. Currently, for every different button function I need, I've duplicated the button and linked it to a separate class. So if I need buttons that link to rules, credits,

  • HT1918 Please send me the website that can changes my security question

    Please apple tell me how to changes it.

  • Help! Premiere Elements 7 won't load project

    Premiere elements 7  won't load my project.  Icon just spins - for about 10 minutes - then it freezes.  Figures that I am so close to finishing!!!  What are my options?  Can I copy the project and open on another computer?  Can I download a newer ver

  • HELP ON PACKAGING

    Am new to LABVIEW. I need some vast help on packaging. I attached some blocks in my application. In the whole application, in those two areas only picture setup were there. The problem is VI file is running perfectly but when i build an exe file and