Use of private class

what is the use of declaring a class as private?

what is the use of declaring a class as private?This is only for inner classes. It allows only the outer class to access it.

Similar Messages

  • Private Class

    I am very new to Java and would like some clarification on a topic. Why do we use private classes? What are the differences between them and public classes? This seems so obvious just by their names but I would like some clarification.
    Thanks,
    Seawall

    use of Private classes:
    (1).we use the private classes for the Private
    constructors to prevent a class from being
    explicitly instantiated by callers. That's what you use a private constructor for, not a private clas.
    private: No other class can instantiate your class.Nothing outside the "body of the top level class (?7.6) that encloses the declaration" can access the class.
    Inability to instantiate is the domain of private constructors, which you have mentioned, but which are not the focus of this thread.

  • How to use the Rectangle class to draw an image and center it in a JPanel

    I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
    I have divided the code into three parts. They are all supposed to be on one file in order to execute.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class CenterRect extends JPanel {
        public static Rectangle srcRect;
        Insets insets = null;
        Image image;
        MyImage imp;
        private double magnification;
        private int dstWidth, dstHeight;
        public CenterRect(MyImage imp){
            insets = getInsets();
            this.imp = imp;
            int width = imp.getWidth();
            int height = imp.getHeight();
            ImagePanel.init();
            srcRect = new Rectangle(0,0, width, height);
            srcRect.setLocation(0,0);
            setDrawingSize(width, height);
            magnification = 1.0;
        public void setDrawingSize(int width, int height) {
            dstWidth = width;
            dstHeight = height;
            setSize(dstWidth, dstHeight);
        public void paintComponent(Graphics g) {
            Image img = imp.getImage();
         try {
                if (img!=null)
                    g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
              srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);
            catch(OutOfMemoryError e) {e.printStackTrace();}
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Opener().openImage();
    class Opener{
        private String dir;
        private String name;
        private static String defaultDirectory;
        JFrame parent;
        public Opener() {
            initComponents();
         public void initComponents(){
            parent = new JFrame();
            parent.setContentPane(ImagePanel.panel);
            parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
            parent.setVisible(true);
        public void openDialog(String title, String path){
            if (path==null || path.equals("")) {
                FileDialog fd = new FileDialog(parent, title);
                defaultDirectory = "dir.image";
                if (defaultDirectory!=null)
                    fd.setDirectory(defaultDirectory);
                fd.setVisible(true);
                name = fd.getFile();
                if (name!=null) {
                    dir = fd.getDirectory();
                    defaultDirectory = dir;
                fd.dispose();
                if (parent==null)
                    return;
            } else {
                int i = path.lastIndexOf('/');
                if (i==-1)
                    i = path.lastIndexOf('\\');
                if (i>0) {
                    dir = path.substring(0, i+1);
                    name = path.substring(i+1);
                } else {
                    dir = "";
                    name = path;
        public MyImage openImage(String directory, String name) {
            MyImage imp = openJpegOrGif(dir, name);
            return imp;
        public void openImage() {
            openDialog("Open...", "");
            String directory = dir;
            String name = this.name;
            if (name==null)
                return;
            MyImage imp = openImage(directory, name);
            if (imp!=null) imp.show();
        MyImage openJpegOrGif(String dir, String name) {
                MyImage imp = null;
                Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
                if (img!=null) {
                    imp = new MyImage(name, img);
                    FileInfo fi = new FileInfo();
                    fi.fileFormat = fi.GIF_OR_JPG;
                    fi.fileName = name;
                    fi.directory = dir;
                    imp.setFileInfo(fi);
                return imp;
    }

    This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
    class MyImage implements ImageObserver{
        private int imageUpdateY, imageUpdateW,width,height;
        private boolean imageLoaded;
        private static int currentID = -1;
        private int ID;
        private static Component comp;
        protected ImageProcessor ip;
        private String title;
        protected Image img;
        private static int xbase = -1;
        private static int ybase,xloc,yloc;
        private static int count = 0;
        private static final int XINC = 8;
        private static final int YINC = 12;
        private int originalScale = 1;
        private FileInfo fileInfo;
        ImagePanel win;
        /** Constructs an ImagePlus from an AWT Image. The first argument
         * will be used as the title of the window that displays the image. */
        public MyImage(String title, Image img) {
            this.title = title;
             ID = --currentID;
            if (img!=null)
                setImage(img);
        public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
             imageUpdateY = y;
             imageUpdateW = w;
             imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
         return !imageLoaded;
        public int getWidth() {
             return width;
        public int getHeight() {
             return height;
        /** Replaces the ImageProcessor, if any, with the one specified.
         * Set 'title' to null to leave the image title unchanged. */
        public void setProcessor(String title, ImageProcessor ip) {
            if (title!=null) this.title = title;
            this.ip = ip;
            img = ip.createImage();
            boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
         width = ip.getWidth();
         height = ip.getHeight();
         if (win!=null && newSize) {
                win = new ImagePanel(this);
        public void draw(){
            CenterRect ic = null;
            win = new ImagePanel(this);
            if (win!=null){
                win.addIC(this);
                win.getCanvas().repaint();
                ic = win .getCanvas();
                win.panel.add(ic);
                int width = win.imp.getWidth();
                int height = win.imp.getHeight();
                Point ijLoc = new Point(10,32);
                if (xbase==-1) {
                    xbase = 5;
                    ybase = ijLoc.y;
                    xloc = xbase;
                    yloc = ybase;
                if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
                    yloc = ybase+20;
                    int x = xloc;
                    int y = yloc;
                    xloc += XINC;
                    yloc += YINC;
                    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                    count++;
                    if (count%6==0) {
                        xloc = xbase;
                        yloc = ybase;
                    int scale = 1;
                    while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
                        if (scale>1) {
                   originalScale = scale;
                   ic.setDrawingSize(width/scale, height/scale);
        /** Returns the current AWT image. */
        public Image getImage() {
            if (img==null && ip!=null)
                img = ip.createImage();
            return img;
        /** Replaces the AWT image, if any, with the one specified. */
        public void setImage(Image img) {
            waitForImage(img);
            this.img = img;
            JPanel panel = ImagePanel.panel;
            width = img.getWidth(panel);
            height = img.getHeight(panel);
            ip = null;
        /** Opens a window to display this image and clears the status bar. */
        public void show() {
            show("");
        /** Opens a window to display this image and displays
         * 'statusMessage' in the status bar. */
        public void show(String statusMessage) {
            if (img==null && ip!=null){
                img = ip.createImage();
            if ((img!=null) && (width>=0) && (height>=0)) {
                win = new ImagePanel(this);
                draw();
        private void waitForImage(Image img) {
        if (comp==null) {
            comp = ImagePanel.panel;
            if (comp==null)
                comp = new JPanel();
        imageLoaded = false;
        if (!comp.prepareImage(img, this)) {
            double progress;
            while (!imageLoaded) {
                if (imageUpdateW>1) {
                    progress = (double)imageUpdateY/imageUpdateW;
                    if (!(progress<1.0)) {
                        progress = 1.0 - (progress-1.0);
                        if (progress<0.0) progress = 0.9;
    public void setFileInfo(FileInfo fi) {
        fi.pixels = null;
        fileInfo = fi;
    }

  • I am getting a NullPointerException when trying to use the Service class

    I am getting a NullPointerException which is as follows
    java.lang.NullPointerException
    file:/K:/Learner/JavaFx2/ProductApplication/dist/run166129449/ProductApplication.jar!/com/product/app/view/viewsingle.fxml
      at com.product.app.controller.ViewSingleController.initialize(ViewSingleController.java:70)
      at javafx.fxml.FXMLLoader.load(Unknown Source)
      at javafx.fxml.FXMLLoader.load(Unknown Source)
    And my View SingleController is as follows
    package com.product.app.controller;
    import com.product.app.model.Product;
    import com.product.app.service.ViewProductsService;
    import com.product.app.util.JSONParser;
    import com.product.app.util.TagConstants;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.ResourceBundle;
    import javafx.collections.ObservableList;
    import javafx.concurrent.Service;
    import javafx.concurrent.Task;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ProgressIndicator;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Region;
    import javafx.stage.Stage;
    import javax.swing.JOptionPane;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;
    * FXML Controller class
    * @author Arun Joseph
    public class ViewSingleController implements Initializable {
        private static String action = "";
        @FXML
        private TextField txtID;
        @FXML
        private TextField txtName;
        @FXML
        private TextField txtPrice;
        @FXML
        private TextArea txtDesc;
        @FXML
        private Region veil;
        @FXML
        private ProgressIndicator p;
        private ViewProductsService service = new ViewProductsService();
        private JSONObject product = null;
        private JSONParser parser = new JSONParser();
        private int pid = 1;
        public void setPid(int pid) {
            this.pid = pid;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
            p.setMaxSize(150, 150);
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
            Product product = new Product();
            service.start();
            ObservableList<Product> products = service.valueProperty().get();
            products.get(pid);
            txtID.textProperty().set(String.valueOf(products.get(pid).getPid()));
            //product = service.valueProperty().get().get(pid);
            //txtID.setText(String.valueOf(product.getPid()));
            txtName.textProperty().set(product.getName());
            txtPrice.textProperty().set(String.valueOf(product.getPrize()));
            txtDesc.textProperty().set(product.getDescription());
        private SomeService someService = new SomeService();
        @FXML
        private void handleUpdateButtonClick(ActionEvent event) {
            action = "update";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleDeleteButtonClick(ActionEvent event) {
            action = "delete";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleCancelButtonClick(ActionEvent event) {
            closeStage();
        private void closeStage() {
            ViewSingleController.stage.close();
        private static Stage stage = null;
        public static void setStage(Stage stage) {
            ViewSingleController.stage = stage;
        private class SomeService extends Service<String> {
            @Override
            protected Task<String> createTask() {
                return new SomeTask();
            private class SomeTask extends Task<String> {
                @Override
                protected String call() throws Exception {
                    String result = "";
                    int success = 0;
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    switch (action) {
                        case "update":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            params.add(new BasicNameValuePair("name", txtName.getText()));
                            params.add(new BasicNameValuePair("price", txtPrice.getText()));
                            params.add(new BasicNameValuePair("description", txtDesc.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_update_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Updated the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                        case "delete":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_delete_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Deleted the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                    return result;

    Time Machine has its own mechanism for deleting files. The number you are seeing may represent a "underflow" or a number of files which exceeds the limit and becomes negative.
    The best way to remove TM files is via the TM interface: select the files and click the Gear and select delete from all backups.
    If you are deleting files on an external drive which once included TM files, it is best to use the terminal and just delete them directly. They go bye-bye without ever seeing the trash bucket.
    Of course, using the terminal is not for everyone.
    What you might be able to do is restore the files from trash and then delete them properly or in smaller bundles.

  • Using a FireFX Class

    I found this class today which is really cool:
    http://www.gskinner.com/blog/archives/2007/11/fire_effect_com.html
    However, I've never used a public class before.  I've been reading up on them all morning.  I'll provide the code for it here as well.  Anyway, the author also provides a sample application using the class; however, it's a bit different than what I've been reading.  He doesn't call the class in his code;however, it seems he has the class in his library, which is news to me.
    Anyway, the biggest thing I'm after is trying to design my own application calling this class and just hardcoding the fire aspects in my application.  However, I'm coming up empty at every angle.  Any help would be much appreciated!
    Here's the class he created:
    * FireFX by Grant Skinner. May 30, 2007
    * Visit www.gskinner.com/blog for documentation, updates and more free code.
    * You may distribute and modify this class freely, provided that you leave this header intact,
    * and add appropriate headers to indicate your changes. Credit is appreciated in applications
    * that use this code, but is not required.
    * Please contact [email protected] for more information.
    package com.gskinner.effects {
                import flash.display.BitmapData;
                import flash.geom.Matrix;
                import flash.geom.Point;
                import flash.geom.ColorTransform;
                import flash.filters.ColorMatrixFilter;
                import flash.filters.BlurFilter;
                import flash.filters.DisplacementMapFilter;
                import flash.display.Sprite;
                import flash.display.MovieClip;
                import flash.events.Event;
                import flash.display.Bitmap;
                import flash.display.DisplayObject;
                public class FireFX extends Sprite {
                            private var _fadeRate:Number=0.4;
                            private var _distortionScale:Number=0.4;
                            private var _distortion:Number=0.5;
                            private var _flameHeight:Number=0.3;
                            private var _flameSpread:Number=0.3;
                            private var _blueFlame:Boolean = false;
                            private var _smoke:Number = 0;
                // private properties:
                            // display elements:
                            private var displayBmp:BitmapData;
                            private var scratchBmp:BitmapData;
                            private var perlinBmp:BitmapData;
                            // geom:
                            private var mtx:Matrix;
                            private var pnt:Point;
                            private var drawColorTransform:ColorTransform;
                            // filters:
                            private var fireCMF:ColorMatrixFilter;
                            private var dispMapF:DisplacementMapFilter;
                            private var blurF:BlurFilter;
                            // other:
                            private var endCount:Number;
                            private var bmpsValid:Boolean=false;
                            private var perlinValid:Boolean=false;
                            private var filtersValid:Boolean=false;
                            private var _target:DisplayObject;
                            public function FireFX() {
                                        var frame:DisplayObject = getChildAt(0);
                                        frame.visible = false;
                                        frame.height = height;
                                        frame.width = width;
                                        scaleX = scaleY = 1;
                                        mtx = new Matrix();
                                        pnt = new Point();
                                        startFire();
                            // getter/setters:
                            override public function set width(value:Number):void {
                                        bmpsValid &&= (value == width);
                                        super.width = value|0;
                            override public function get width():Number {
                                        return super.width;
                            override public function set height(value:Number):void {
                                        bmpsValid &&= (value == height);
                                        super.height = value|0;
                            override public function get height():Number {
                                        return super.height;
                            [Inspectable(defaultValue=0.4,name='fadeRate (0-1)')]
             * Sets the rate that flames fade as they move up. 0 is slowest, 1 is fastest.
             * @default 0.4
                            public function set fadeRate(value:Number):void {
                                        filtersValid &&= (value == _fadeRate);
                                        _fadeRate = value;
                            public function get fadeRate():Number {
                                        return _fadeRate;
                            [Inspectable(defaultValue=0.4,name='distortionScale (0-1)')]
             * Sets the scale of flame distortion. 0.1 is tiny and chaotic, 1 is large and smooth.
             * @default 0.4
                            public function set distortionScale(value:Number):void {
                                        perlinValid &&= (value == _distortionScale);
                                        _distortionScale = value;
                            public function get distortionScale():Number {
                                        return _distortionScale;
                            [Inspectable(defaultValue=0.4,name='distortion (0-1)')]
             * Sets the amount of distortion. 0.1 is little, 1 is chaotic.
             * @default 0.4
                            public function set distortion(value:Number):void {
                                        filtersValid &&= (value == _fadeRate);
                                        _distortion = value;
                            public function get distortion():Number {
                                        return _distortion;
                            [Inspectable(defaultValue=0.3,name='flameHeight (0-1)')]
             * Sets the how high the flame will burn. 0 is zero gravity, 1 is a bonfire.
             * @default 0.3
                            public function set flameHeight(value:Number):void {
                                        perlinValid &&= (value == _flameHeight);
                                        _flameHeight = value;
                            public function get flameHeight():Number {
                                        return _flameHeight;
                            [Inspectable(defaultValue=0.3,name='flameSpread (0-1)')]
             * Sets the how much the fire will spread out around the target. 0 is no spread, 1 is a lot.
             * @default 0.3
                            public function set flameSpread(value:Number):void {
                                        filtersValid &&= (value == _flameSpread);
                                        _flameSpread = value;
                            public function get flameSpread():Number {
                                        return _flameSpread;
                            [Inspectable(defaultValue=false,name='blueFlame')]
             * Indicates whether it should use a blue or red flame.
             * @default false
                            public function set blueFlame(value:Boolean):void {
                                        filtersValid &&= (value == _blueFlame);
                                        _blueFlame = value;
                            public function get blueFlame():Boolean {
                                        return _blueFlame;
                            [Inspectable(defaultValue=0,name='smoke (0-1)')]
             * Sets the amount of smoke. 0 little, 1 lots.
             * @default 0
                            public function set smoke(value:Number):void {
                                        filtersValid &&= (value == _smoke);
                                        _smoke = value;
                            public function get smoke():Number {
                                        return _smoke;
                            [Inspectable(defaultValue='',name='target')]
             * Sets the amount of smoke. 0 little, 1 lots.
             * @default
                            public function set targetName(value:String):void {
                                        var targ:DisplayObject = parent.getChildByName(value);
                                        if (targ == null) {
                                                    try { targ = parent[value] as DisplayObject; }
                                                    catch (e:*) {}
                                        target = targ;
             * Defines the shape of the fire. The fire will burn upwards, so it should be near the bottom, and centered in the FireFX component.
             * @default
                            public function set target(value:DisplayObject):void {
                                        _target = value;
                                        clear();
                            public function get target():DisplayObject {
                                        return _target;
             * Clears the fire.
                            public function clear():void {
                                        if (displayBmp) {
                                                    displayBmp.fillRect(displayBmp.rect,0);
             * Stops the fire effect after letting it burn down over 20 frames.
                            public function stopFire():void {
                                        // let the fire burn down for 20 frames:
                                        if (endCount == 0) { endCount = 20; }
                            private function updateBitmaps():void {
                                        if (displayBmp) {
                                                    displayBmp.dispose();
                                                    displayBmp = null;
                                                    scratchBmp.dispose();
                                                    scratchBmp = null;
                                                    perlinBmp.dispose();
                                                    perlinBmp = null;
                                        displayBmp = new BitmapData(width, height, true, 0);
                                        scratchBmp = displayBmp.clone();
                                        perlinBmp = new BitmapData(width*3, height*3, false, 0);
                                        while (numChildren) { removeChildAt(0); }
                                        addChild(new Bitmap(displayBmp));
                                        updatePerlin();
                                        updateFilters();
                                        bmpsValid = true;
                            private function updatePerlin():void {
                                        perlinBmp.perlinNoise(30*_distortionScale,20*_distortionScale,1,-Math.random()*1000|0,fals e,true,1|2,false);
                                        perlinBmp.colorTransform(perlinBmp.rect,new ColorTransform(1,  1-_flameHeight*0.5  ,1,1,0,0,0,0));
                                        perlinValid = true;
                            function updateFilters():void {
                                        if (_blueFlame) {
                                                    fireCMF = new ColorMatrixFilter([0.8-0.55*_fadeRate,0,0,0,0,
                                                                                                                                                     0,0.93-0.48*_fadeRate,0,0,0,
                                                                                                                                                     0,0.1,0.96-0.35*_fadeRate,0,0,
                                                                                                                                                     0,0.1,0,1,-25+_smoke*24]);
                                                    drawColorTransform = new ColorTransform(0,0,0,1,210,240,255,0);
                                        } else {
                                                    fireCMF = new ColorMatrixFilter([0.96-0.35*_fadeRate,0.1,0,0,-1,
                                                                                                                                                     0,0.9-0.45*_fadeRate,0,0,0,
                                                                                                                                                     0,0,0.8-0.55*_fadeRate,0,0,
                                                                                                                                                     0,0.1,0,1,-25+_smoke*24]);
                                                    drawColorTransform = new ColorTransform(0,0,0,1,255,255,210,0);
                                        dispMapF = new DisplacementMapFilter(perlinBmp,pnt,1,2,14*_distortion,-30,"clamp");
                                        blurF = new BlurFilter(32*_flameSpread,32*_flameSpread,1);
                                        filtersValid = true;
                            private function startFire():void {
                                        endCount = 0;
                                        addEventListener(Event.ENTER_FRAME,doFire);
                            private function doFire(evt:Event):void {
                                        if (_target == null) { return; }
                                        if (!bmpsValid) { updateBitmaps(); }
                                        if (!perlinValid) { updatePerlin(); }
                                        if (!filtersValid) { updateFilters(); }
                                        if (endCount == 0) {
                                                    var drawMtx:Matrix = _target.transform.matrix;
                                                    drawMtx.tx = _target.x-x;
                                                    drawMtx.ty = _target.y-y;
                                                    scratchBmp.fillRect(scratchBmp.rect,0);
                                                    drawColorTransform.alphaOffset = -Math.random()*200|0;
                                                    scratchBmp.draw(_target,drawMtx,drawColorTransform,"add");
                                                    scratchBmp.applyFilter(scratchBmp,scratchBmp.rect,pnt,blurF);
                                                    displayBmp.draw(scratchBmp,mtx,null,"add");
                                        dispMapF.mapPoint = new Point( -Math.random()*(perlinBmp.width-displayBmp.width)|0, -Math.random()*(perlinBmp.height-displayBmp.height)|0 );
                                        displayBmp.applyFilter(displayBmp,displayBmp.rect,pnt,dispMapF);
                                        displayBmp.applyFilter(displayBmp,displayBmp.rect,pnt,fireCMF);
                                        if (endCount != 0 && --endCount == 0) {
                                                    removeEventListener(Event.ENTER_FRAME,doFire);
    Then, this is the sample application he gave:
    import fl.controls.Slider;
    import fl.controls.Label;
    import fl.events.SliderEvent;
    var params:Array = ["distortion","distortionScale","fadeRate","flameHeight","flameSpread","smoke"]
    var l:uint = params.length;
    for (var i:uint=0; i<l; i++) {
                var label:TextField = new TextField();
                label.textColor = 0;
                label.text = params[i];
                label.width = 140;
                label.x = 350;
                label.y = 55+50*i;
                addChild(label);
                label = new TextField();
                label.textColor = 0x999999;
                label.text = "0.35";
                label.name = params[i]+"fld";
                label.width = 30;
                label.x = 490;
                label.y  = 55+50*i;
                addChild(label);
                var slider:Slider = new Slider();
                slider.name = params[i];
                slider.minimum = -2;
                slider.maximum = 2;
                slider.addEventListener(SliderEvent.THUMB_DRAG,handleSlider);
                addChild(slider);
                slider.x = 350;
                slider.width = 170;
                slider.y = 75+50*i;
                slider.snapInterval = 0.05;
                slider.value = 0.35;
                fireFX[params[i]] = 0.35;
    function handleSlider(evt:SliderEvent):void {
                fireFX[evt.target.name] = evt.target.value;
                (getChildByName(evt.target.name+"fld") as TextField).text = String(evt.target.value);
    blueFlame.addEventListener(Event.CHANGE,handleCheckBox);
    hideText.addEventListener(Event.CHANGE,handleCheckBox);
    function handleCheckBox(evt:Event):void {
                fireFX.blueFlame = blueFlame.selected;
                obj.visible = !hideText.selected;
    Thanks again.

    Looks like he has fireFX instance on the timeline. Most probably this instances symbol base class is com.gskinner.effects.FireFX
    You just need to create a directory structure that reflects his package:
    com/gskinner/effects/
    where you place his FireFX.as
    Or, alternatively, you can remove package path from the class header and place FireFx where all you classes (or your application) are:
    package com.gskinner.effects {
    to
    package {
    Then you will just need to instantiate the class.

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • Why use an Abstract Class ?

    I am new to Java and for some reason I can't get my head around why to use an abstract class. I understand that an abstract class is something like:
    public abstract class Food{ // abstract class
    public void eat(){
    // stub
    public class Apple extends Food{
    public void eat(){
    // Eat an apple code
    }So basically the idea above is that you can eat an "apple" but you can't eat "food" because you can't instantiate an abstract class.
    I understand what an abstract class is and how to write one. What I don't understand is why you would use it? It looks to me like I could have just created a normal class called "Food" and just not instantiated it. What are the benefits of using an abstract class?

    807479 wrote:
    I am new to Java and for some reason I can't get my head around why to use an abstract class.One of the first books I ever read about Object-Oriented design contained the following quote from [url http://en.wikipedia.org/wiki/Lucius_Cary,_2nd_Viscount_Falkland]Lord Falkland:
    "When it is not necessary to make a decision, it is necessary +not+ to make a decision."
    It took me quite a while to understand, but it's all about flexibility: As soon as you cast something in stone, you lose the ability to change it later on if something better/more appropriate comes along. Interfaces and abstract classes are all about delaying that decision.
    As jverd said, interfaces allow you to specify what is required without defining the how; and as ErasP said, abstract classes are usually incomplete: ie, they define some of the 'how', but not all of it.
    What is most important about abstract classes though is that they cannot exist on their own: They must be extended by a concrete class that completes the 'how' before they can be instantiated and, as such, they declare the intent of the designer.
    One of the most important uses of abstract classes is as "skeleton implementations" of interfaces, and there are a lot of examples of these in the Java Collections hierarchy. My favourite is probably AbstractList, which contains a skeleton implementation of a List. Because it exists, I can create a class that wraps an array as a List with very little code, viz:public final class ArrayAsList<T>()
       extends AbstractList<T>
       private final T[] values;
       public ArrayAsList(T... values) {
          this.values = values;
       @Override
       public T get(int index) {
          return values[index];
       @Override
       public T set(int index, T element) {
          T value = get(index);
          values[index] = element;
          return value;
       @Override
       public int size() {
          return values.length;
    };and somewhere else, I can use it:   List<String> letters =
          new ArrayAsList<String>("a", "b", "c");or perhaps, more practically:   List<String> words = new ArrayAsList<String>(
          bigTextString.split(" +") );Now that may not seem like a big deal to you, but given all that Lists can do, it's actually a very powerful bit of code. The above example is from "Effective Java" (p.95).
    HIH
    Winston

  • 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.

  • Did the Java Writers Get a Little Happy with Memory Use in String class?

    I mean that question half jokingly.
    Taking a look at the String class code, I saw the following (below).
    Why is there an int for offset and an int for count?
    String is immutable, why not just return value.length for the count?
    And what is the offset for?
    Thanks!
    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence
        /** The value is used for character storage. */
        private final char value[];
        /** The offset is the first index of the storage that is used. */
        private final int offset;
        /** The count is the number of characters in the String. */
        private final int count;
        /** Cache the hash code for the string */
        private int hash; // Default to 0PS: a second look kinda verifies it too.
    in the constructor ,count is even defined as value.length.
        public String(char value[]) {
         int size = value.length;
         this.offset = 0;
         this.count = size;
         this.value = Arrays.copyOf(value, size);
        }

    You don't get the choice. The arrays are shared
    whenever you do substring.Yea, thats my point. I think most Strings are unique.
    Id be very surprised if even 2% of all String use was
    a result of a substring.The wrapper classes use it for parsing.
    File uses it for getName and getParent.
    String uses it for trim.
    Class uses it for resolving names.
    Regex uses it.
    etc. ...
    Now, I don't know what percentage of usage all that amounts to, but it IS heavily used.
    So your desire to gain the 2 bytes back would cost enough byte every time substring is used that it might end up costing far more than the 8 bytes you save.

  • 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

  • What is the use of private static method/variable?

    Hi All,
    I have read lots of books and tried lots of things but still not very clear on the
    topic above.
    When exactly do we HAVE to use private static methods?
    private implies its only for class, cannot be accessed outside.
    But then static means, it can be accessed giving classname.method.
    They seem to be contradicting each other.
    Any examples explaining the exact behaviour will be well appreciated.
    Thanks,
    Chandra Mohan

    Static doesn't really "mean" that the method/field is intended for use outside the class - that is exactly what the access modifier is for.
    Static implies that it is for use in relation to the class itself, as opposed to an instance of the class.
    One good example of a private static method would be a utility method that is (only) invoked by other (possibly public) static methods; it is not required outside the class (indeed, it might be dangerous to expose the method) but it must be called from another static method so it, in turn, must be static.
    Hope this helps.

  • Why can't I use Get LV Class Default Value in a dynamic VI?

    I am attempting to override a VI that uses "Get LV Class Default Value" and getting an error that I don't understand.  My parent class, "ANT Message Class", has two children - "ANT Command Class" and "ANT Response Class".  The children share a lot of data and functionality, including the factory pattern that the parent class' "Load Message Class" VI implements (see image).  I would like to override this VI with a Command version and a Response version, which would simply call the Message version with their respective classes overriding the dynamic input and output terminals.  However, I am getting the error "Front Panel Terminal 'ANT Message Class Out': Run-time type not propagated from dynamic input to dynamic output."
    Not sure how to get around this one.  Any ideas?
    Thanks,
    -Jamie 
    Solved!
    Go to Solution.
    Attachments:
    Get LV Class Default Value in dynamic VI.png ‏179 KB

    The To More Specific node is dealing with compile-type inference. In this case, you are loading a default instance from disk and then attempting to cast to the base Message class. However the type you are casting to is going to a dynamic output - this gives the compiler no assurances that the input class at run-time on the dynamic input will be the same as the output type; only that it will be a type at the top of the hierarchy. Dyanmic dispatch inputs/outputs must be the same type to guarantee some form of type safety.
    You need the Preserve node there so that you can guarantee the class at both dynamic dispatch terminals will be the same type.
    However this is probably not the best mechanism for a factory method. Factory methods should ideally be static; their job is to provide an instance of the right type (e.g loaded by path as per your example) and you don't need an instance of a class to do that. The only reason I can think of to over-ride said functionailty in a dynamic dispatch method is to provide some form of custom construction for the creation of the type. If all you are creating is an instance with nothing but the default private data then there is no reason to over-ride in the child classes.
    EDIT: Another post collision. nathand is on the money with this one.

  • Why can't this program access the private class

    All,
    If you could give me some help I would appreciate it, as I have been worrying this issue for some time now and cannot figure out why this program will not compile. It tells me that there are a number of errors, and it appears that these errors are due to the fact that it will not allow me to reach from the private class to the primary for variables. Now, I have seen another program that is very similar and it does not have these issues. IF someone would explain to me what is going on here I think that I could fix it. Thanks
       import java.io.*;
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
       import java.text.*;
       import java.util.*;
       import java.lang.*;
        public class MortgageGUIv4_1 extends JFrame
           public static void main(String[] args)
             new MortgageGUIv4_1();
          double MP, calcAPR, APR, adjustAPR, annualAPR;
          double monthTerm, userTerm;
          double userPrin;
          boolean user = false;
          String headers = "Payment No. \t\tRemainging Balance \tInterest Paid";
          String []loanRates = {"7 years at 5.35%,15 years at 5.5, 30 years at 5.75%"};
           public MortgageGUIv4_1()
             ButtonListener b1 = new ButtonListener();
             JPanel firstRow = new JPanel();
             JPanel fourthRow = new JPanel();
             JPanel fifthRow = new JPanel();
             JPanel sixthRow = new JPanel();
             JPanel seventhRow = new JPanel();
             JPanel fieldPanel = new JPanel();
             JPanel buttonPanel = new JPanel();
             JPanel buttonPanel3 = new JPanel();
             JLabel userPrinLabel = new JLabel("Principle:  ");
             JTextField userPrinvalue = new JTextField(10);
             ButtonGroup loanGroup = new ButtonGroup();   
             JLabel outputLabel = new JLabel("Click to see your payment");
             JButton buttonSubmit = new JButton("Submit");
             buttonSubmit.addActionListener(b1);
             JLabel outputLabel3 = new JLabel("Click here to clear Data");
             JButton buttonClear = new JButton("Clear");
             buttonClear.addActionListener(b1);
             JLabel mortgagePayment = new JLabel ("Your Monthly Payments are");
             JTextField totPayment = new JTextField(10);
             JComboBox termRateBx = new JComboBox(loanRates);
             JLabel termRateLbl = new JLabel("Select a Term and Rate from the options listed");
             JTextArea pymntTable = new JTextArea(headers, 10, 50);
             JScrollPane scroll = new JScrollPane(pymntTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
             try
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                 catch(Exception e)
                   JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this applicatoin.", "Error",
                      JOptionPane.INFORMATION_MESSAGE);
             MortgageGUIv4_1 winPane = new MortgageGUIv4_1();
             winPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             winPane.setSize(300,300);
             winPane.setTitle("Dan's Mortgage GUI System");
             winPane.setResizable(false);
             winPane.setLocation(200,100);
             winPane.setVisible(true);
             Container cont = getContentPane();
             cont.setLayout((new BorderLayout()));
             fieldPanel.setLayout(new GridLayout(8,1));
             FlowLayout rowSetup = new FlowLayout(FlowLayout.CENTER, 5,3);
             firstRow.setLayout(rowSetup);
             fourthRow.setLayout(rowSetup);
             fifthRow.setLayout(rowSetup);
             sixthRow.setLayout(rowSetup);
             seventhRow.setLayout(rowSetup);
             buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
             buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
             firstRow.add(userPrinLabel);
             firstRow.add(userPrinvalue);
             fourthRow.add(mortgagePayment);
             fourthRow.add(totPayment);
             fifthRow.add(termRateBx);
             fifthRow.add(termRateLbl);
             sixthRow.add(scroll);
             fieldPanel.add(firstRow);
             fieldPanel.add(fourthRow);
             fieldPanel.add(fifthRow);
             fieldPanel.add(sixthRow);
             fieldPanel.add(seventhRow);
             buttonPanel.add(buttonSubmit);
             buttonPanel.add(buttonClear);
             cont.add(fieldPanel, BorderLayout.CENTER);
             cont.add(buttonPanel, BorderLayout.SOUTH);
           private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                Object source = e.getSource();
             //used the term user because this is the user input.  When the user inputs a correct value then the program moves on
                do
                   //captures the user data entered in the text field and converts it to double
                   String enterAmount = userPrinvalue.getText();
                   userPrin = Double.parseDouble(enterAmount);
                   if(userPrin <0)
                      JOptionPane.showMessageDialog(null,"The Principle value is out of range.  Please choose a value that is greater than 0", "Error",
                         JOptionPane.INFORMATION_MESSAGE);
                   else user=true;
                }while (!user);
                if(source == buttonSubmit)
                //captures the user data entered in the text field and converts it to double
                   String enterAmount = userPrinvalue.getText();
                   userPrin = Double.parseDouble(enterAmount);
                   if(selection.equals(loanRates[0]))
                      APR = 535 / (12 * 100);  //The APR is converted from whole number to % and reduced to the monthly rate
                      monthTerm = 7 * 12;  //The Term must be converted to months
                      adjustAPR= 1 + APR;
                      calcAPR = 1 - Math.pow(adjustAPR, -monthTerm);
                   if(selection.equals(loanRates[1]))
                      APR = 550 / (12 * 100);  //The APR is converted from whole number to % and reduced to the monthly rate
                      monthTerm = 15 * 12;  //The Term must be converted to months
                      adjustAPR= 1 + APR;
                      calcAPR = 1 - Math.pow(adjustAPR, -monthTerm);
                   if(selection.equals(loanRates[2]))
                      APR = 575 / (12 * 100);  //The APR is converted from whole number to % and reduced to the monthly rate
                      monthTerm = 30 * 12;  //The Term must be converted to months
                      adjustAPR= 1 + APR;
                      calcAPR = 1 - Math.pow(adjustAPR, -monthTerm);
                   MP = userPrin * (APR / calcAPR);
                   DecimalFormat twodigits = new DecimalFormat("#,###.##");
                //The system will now render the monthly payment amount
                   totPayment.setText("$" + twodigits.format(MP));
                   double loanBal, newLoanBal, mnthlyIntPd, mnthlyPrinPd;
                   for (int i = 0; i >= monthTerm;i++)
                      newLoanBal = loanBal;
                      mnthlyIntPd = loanBal * APR;
                      mnthlyPrinPd = MP - mnthlyIntPd;
                      loanBal = loanBal - mnthlyPrinPd;
                      pymntTable.append("\n"+i+ "\t\t" + twodigits.format(loanBal)+ "\t\t" + twodigits.format(mnthlyIntPd));
                if(source == buttonClear)
                   userPrinvalue.setText("");
                   pymntTable.setText(headers);
       }Dan

    Thank you one and all, in part to what you said here I when through and obviously had to make some serious changes to the code. Now it will compile however, when I try to run it I am getting the following error. do not use MortgageGUIv4_1.add() use MortgageGUIv4.1.getContentPane.add instead. I am at a loss for this one, as when I looked it up the only difference was that the one is awt and the other is swing. Could someone please let me know what I am missing.
    Thanks
    Dan
       import java.io.*;
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
       import javax.swing.event.*;
       import javax.swing.border.*;
       import java.text.*;
       import java.util.*;
       import java.lang.*;
        public class MortgageGUIv4_1 extends JFrame
           public static void main(String[] args)
             new MortgageGUIv4_1();
          double MP, calcAPR, APR, adjustAPR, annualAPR;
          double monthTerm, userTerm;
          double userPrin;
          boolean user = false;
          String headers = "Payment No. \t\tRemainging Balance \tInterest Paid";
          String loanRates[] = {"7 years at 5.35%","15 years at 5.5", "30 years at 5.75%"};
              private JLabel userPrinLabel, outputLabel, outputLabel3, mortgagePayment, termRateLbl;
              private JTextField userPrinvalue, totPayment;
              private JButton buttonClear, buttonSubmit;
              private JComboBox termRateBx = new JComboBox(loanRates);
              private JTextArea pymntTable;
              private JScrollPane scroll = new JScrollPane(pymntTable);
           public MortgageGUIv4_1()
             ButtonListener b1 = new ButtonListener();
               this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             this.setSize(900,500);
             this.setTitle("Dan's Mortgage GUI System");
             this.setLocation(240,0);
             this.setVisible(true);
             JPanel winPane = new JPanel();
             JPanel userPrinciple = new JPanel();
             userPrinLabel = new JLabel("Principle:  ");
             userPrinvalue = new JTextField(10);
             userPrinciple.add(userPrinLabel);
             userPrinciple.add(userPrinvalue);
             ButtonGroup loanGroup = new ButtonGroup();
             outputLabel = new JLabel("Click to see your payment");
             buttonSubmit = new JButton("Submit");
             buttonSubmit.addActionListener(b1);
             outputLabel3 = new JLabel("Click here to clear Data");
             buttonClear = new JButton("Clear");
             buttonClear.addActionListener(b1);
               JPanel results = new JPanel();
               mortgagePayment = new JLabel ("Your Monthly Payments are");
             totPayment = new JTextField(10);
               results.add(mortgagePayment);
             results.add(totPayment);
               JPanel comboBx = new JPanel();
             termRateLbl = new JLabel("Select a Term and Rate from the options listed");
               comboBx.add(termRateBx);
             comboBx.add(termRateLbl);
             pymntTable = new JTextArea(headers, 10, 50);
             JScrollPane scroll = new JScrollPane(pymntTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
             try
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                 catch(Exception e)
                   JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this applicatoin.", "Error",
                      JOptionPane.INFORMATION_MESSAGE);
             winPane.add(userPrinciple);
             winPane.add(comboBx);
             winPane.add(results);
               winPane.add(scroll);
               winPane.add(outputLabel);
               winPane.add(buttonSubmit);
             winPane.add(outputLabel3);
             winPane.add(buttonClear);
               this.add(winPane);
           private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                Object source = e.getSource();
                String selection = (String)termRateBx.getSelectedItem();
             //used the term user because this is the user input.  When the user inputs a correct value then the program moves on
                do
                   //captures the user data entered in the text field and converts it to double
                   String enterAmount = userPrinvalue.getText();
                   userPrin = Double.parseDouble(enterAmount);
                   if(userPrin <0)
                      JOptionPane.showMessageDialog(null,"The Principle value is out of range.  Please choose a value that is greater than 0", "Error",
                         JOptionPane.INFORMATION_MESSAGE);
                   else user=true;
                }while (!user);
                if(source == buttonSubmit)
                //captures the user data entered in the text field and converts it to double
                   String enterAmount = userPrinvalue.getText();
                   userPrin = Double.parseDouble(enterAmount);
                   if(selection.equals(loanRates[0]))
                      APR = 535 / (12 * 100);  //The APR is converted from whole number to % and reduced to the monthly rate
                      monthTerm = 7 * 12;  //The Term must be converted to months
                      adjustAPR= 1 + APR;
                      calcAPR = 1 - Math.pow(adjustAPR, -monthTerm);
                   if(selection.equals(loanRates[1]))
                      APR = 550 / (12 * 100);  //The APR is converted from whole number to % and reduced to the monthly rate
                      monthTerm = 15 * 12;  //The Term must be converted to months
                      adjustAPR= 1 + APR;
                      calcAPR = 1 - Math.pow(adjustAPR, -monthTerm);
                   if(selection.equals(loanRates[2]))
                      APR = 575 / (12 * 100);  //The APR is converted from whole number to % and reduced to the monthly rate
                      monthTerm = 30 * 12;  //The Term must be converted to months
                      adjustAPR= 1 + APR;
                      calcAPR = 1 - Math.pow(adjustAPR, -monthTerm);
                   MP = userPrin * (APR / calcAPR);
                   DecimalFormat twodigits = new DecimalFormat("#,###.##");
                //The system will now render the monthly payment amount
                   totPayment.setText("$" + twodigits.format(MP));
                   double loanBal = userPrin, newLoanBal, mnthlyIntPd, mnthlyPrinPd;
                   for (int i = 0; i >= monthTerm;i++)
                      newLoanBal = loanBal;
                      mnthlyIntPd = loanBal * APR;
                      mnthlyPrinPd = MP - mnthlyIntPd;
                      loanBal = loanBal - mnthlyPrinPd;
                      pymntTable.append("\n"+i+ "\t\t" + twodigits.format(loanBal)+ "\t\t" + twodigits.format(mnthlyIntPd));
                if(source == buttonClear)
                   userPrinvalue.setText("");
                   pymntTable.setText(headers);
       }

  • Use of private methods

    Can someone tell me when a java program would use private methods? I understand that use of private instance variables is the norm and when extending a class, the use of the public methods is required to access the data. But when would it be necessary to use a private method? Thanks.

    Okay, so you create a class. And some other class uses that class.
    public class Useful {
      public void doSomethingUseful() {
    public class User {
      // Use a Useful to do something useful
      Useful u = new Useful();
      u.doSomethingUseful();
    }Now, you could put a whole bunch of krap into the single doSomethingUseful method, or you could be smart and break its work down into smaller methods, which each method having it's own responsibility. Those methods would be private, because there's no reason to expose the implementation details of the public method.

  • Hi ppl..doubts on private class

    Final warning.  Please use a more meaningful subject in future.  And please don't use "hi ppl" in the subject.
    hi ppl,
              To access the private class one method is to declare the methods in public section and data in private section.But how can i access fi i declare the methods and data in private section itself.I think,the answer is with in that class itself.below is the code i sis so far,but iam unable to achieve the value that is in variable 'sum'.pls iam a new to oops concept..guide me
    REPORT  Y_OOPS_FOR_DEMO.
    * public section.
    data: a type i value 1,
            b type i value 2,
           C type i,
           SUM TYPE I.
    class cl definition.
      private section.
    methods: zdev importing c type i
    *                        D TYPE I
                    exporting a type i
                             b type i.
    endclass.
    class cl implementation.
      method zdev.
    sum = a + b.
    endmethod.
    endclass.
    data: m type i.
    class dev1 definition inheriting from cl.
    public section.
    data: k type i value 10.
    methods: asm.
    endclass.
    class dev1 implementation.
    method asm .
    m = sum + k.
    write:/ 'THE VALUE OF sum IS ', m.
      endmethod.
      endclass.
    DATA: OBJ TYPE REF TO dev1.
    * DATA: OBJ1 TYPE REF TO cl.
    START-OF-SELECTION.
    CREATE OBJECT: OBJ.
    CREATE OBJECT: OBJ1.
    END-OF-SELECTION.
    CALL METHOD OBJ->asm.
    Edited by: Matt on Dec 1, 2008 4:21 PM
    Edited by: Matt on Dec 1, 2008 4:37 PM

    Hello Priyank
    My first recommendation is to use the Pretty-Printer option because otherwise your report looks like classical spaghetti coding.
    Your variable SUM is always accessible because it is a global variable of the report and by no means linked to any class. Your PUBLIC SECTION must be within the class itself.
    Your class is a local public class because you can instantiate it using CREATE OBJECT statement. A private class cannot be instantiated directly but here you need to have a static (factory) method which does the instantiation for you.
    The private method ZDEV is never called and therefore useless. Since the public instance attribute SUM has no initial value and its is never changed its value is always equal 0. Therefore within method ASM the value of M is always equal to K (= 10). Thus, the output of you report will always be:
    THE VALUE OF sum IS 10
    *& Report  Y_OOPS_FOR_DEMO
    REPORT  y_oops_for_demo.
    "* public section.
    "DATA: a TYPE i VALUE 1,
    "       b TYPE i VALUE 2,
    "      c TYPE i,
    "      sum TYPE i.
    *       CLASS cl DEFINITION
    CLASS cl DEFINITION.
      PUBLIC SECTION.  " $TMP added
    DATA: a TYPE i VALUE 1,
           b TYPE i VALUE 2,
          c TYPE i,
          sum TYPE i.
      PRIVATE SECTION.
        METHODS: zdev IMPORTING c TYPE i
    *                        D TYPE I
                        EXPORTING a TYPE i
                                 b TYPE i.
    ENDCLASS.                    "cl DEFINITION
    *       CLASS cl IMPLEMENTATION
    CLASS cl IMPLEMENTATION.
      METHOD zdev.
        sum = a + b.
      ENDMETHOD.                    "zdev
    ENDCLASS.                    "cl IMPLEMENTATION
    DATA: m TYPE i.
    *       CLASS dev1 DEFINITION
    CLASS dev1 DEFINITION INHERITING FROM cl.
      PUBLIC SECTION.
        DATA: k TYPE i VALUE 10.
        METHODS: asm.
    ENDCLASS.                    "dev1 DEFINITION
    *       CLASS dev1 IMPLEMENTATION
    CLASS dev1 IMPLEMENTATION.
      METHOD asm .
        m = sum + k.
        WRITE:/ 'THE VALUE OF sum IS ', m.
      ENDMETHOD.                    "asm
    ENDCLASS.                    "dev1 IMPLEMENTATION
    DATA: obj TYPE REF TO dev1.
    * DATA: OBJ1 TYPE REF TO cl.
    START-OF-SELECTION.
      CREATE OBJECT: obj.
      CREATE OBJECT: obj1.
    END-OF-SELECTION.
      CALL METHOD obj->asm.
    Regards
      Uwe

Maybe you are looking for

  • Need to create a message INVOIC from transaction MIRO

    Hy, try to find an answer on following prob. I need to send the billing information from transaction MIRO to another system. They want to have a INVOIC02. I know how to create a message but i have not found a solution (wich function) to create a INVO

  • Reports published don't connect to DB in Infoview do connect in CR 2008 dsn

    Reports that execute in Crystal Reports 2008 designer do not execute in Infoview after being published.  The CR 2008 designer is connected to a SQL SERVER 2005 database. Once published, the Infoview version of the report never connects to the databas

  • Ciscoworks LMS 3.2 - Compliance mgmt negation problem

    Hi, Strange problem, that I am sure is being caused by me. Basically trying to run an advanced Compliance mgmt job, looking for a set of pre-requisites (this is working) and then removing all non compliance SNMP community strings from a sample device

  • Extract DATE from TEXT column

    Dear all, I have the following comment in column in one my table. Is there a smart way to extract the DATE from the text, It may be in any date format. 'My comments (written submissions sent on 29-SEP-2006)' 'My comments are 24 September 2009 9.30 '

  • Question about audiobook download

    I downloaded an audiobook that shows I have part 1of 2 and part 2 of 2 downloaded.  However it will not let me open part 2 of 2.  It will only let me listen to 2 of 2 which is chapter 20.  What do I do???