Java programming baseclass

I haven't had lot of experience with java.I am currently trying to understand an application that is written using java and the frontend of the application is swings.I noticed that every package has a base class and it is derived by all the other sub classes.  Could you please provide me with an example which can explain in detail how this is helpful and when this is used.Thanks for your help.
g46905Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

g46905Author Commented:
CEHJ,
       The article you sent contains the informatin about the OOP concept.But, I am looking for a real  simple example that would have a base class and then derive the other objects from that class.If you could send me one, I would really appreicate it.Thanks for your help.
0
sharath_kulalCommented:
interface Vehicle{
    public String getType();
    public int getWheels();
    public int getCapacity();
}

abstract class TwoWheeler implements Vehicle{
    public String getType() {
        return "Two Wheeler";
    }
    public int getWheels() {
        return 2;
    }
}

abstract class FourWheeler implements Vehicle{
    public String getType() {
        return "Four Wheeler";
    }
    public int getWheels() {
        return 4;
    }
}

class Bike extends TwoWheeler{
    public int getCapacity() {
        return 2;
    }
}

class Car extends FourWheeler{
    public int getCapacity() {
        return 4;
    }
}

Now since Car extends Four Wheeler it only needs to implement getCapacity, since the rest of the methods are already implemented in FourWheeler.

if you need to define a new class say Moped. we would extend TwoWheeler.

Hope this helps.
0
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

CEHJCommented:
class A {
      public void foo() {
            System.out.println(getClass());
      }
}


class B extends A {
}

public class TestInheritance {
      public static void main(String[] args) {
            A a = new A();
            a.foo();
            B b = new B();
            b.foo();
      }
}

Save it as TestInheritance.java and compile and run it
0
CEHJCommented:
>>abstract class TwoWheeler

Not really a good candidate for an abstract class (and some others) - but let's keep it simple for now ...
0
Mayank SAssociate Director - Product EngineeringCommented:
It is normally used in cases where you want several implementations of the same thing. Let's' say you have an application which does some business processing on some data. Now this data can be stored anywhere, it could be a simple text-file, XML file, data-base or any other kind of store. In such a case, let's say you use:

public interface DataStore
{
  public ArrayList getData () ; // let's assume this method gets some data

}

public class FileStore extends DataStore
{
  public ArrayList getData ()
  {
    // get the data from the data-base
  }
}

public class DatabaseStore extends DataStore
{
  public ArrayList getData ()
  {
    // get the data from the data-base
  }
}

In the business-logic part of the code (which might be a separate component), you can use an interface reference and make it refer to any of the implementing class's objects, and it would be independent of the data-store:

DataStore obj = new FileStore () ; // or new DatabaseStore () ;

If you have some base code which will be common to FileStore and DatabaseStore, you can make the interface as an abstract base class.

But still, if you write it this way [DataStore obj = new FileStore () ;], it defeats the purpose of having inheritance. A better option is to decide upon run-time as to which data-store implementation you want to use. Let's say you store it in a properties-file, as:

STORE_IMPLEMENTATION = File

In the code, you can do:

DataStore obj ;
// read the value of STORE_IMPLEMENTATION from a properties-file into a variable called 'choice'

if ( choice.equals ( "File" ) )
  obj = new FileStore () ;

else if ( choice.equals ( "DB" ) )
  obj = new DatabaseStore () ;

This way, you can change on run-time (without a change in code), the store-implementation that you want to use. If you follow this approach, the code is a little bit generic but still, the number of available options you have are hard-coded in the code (it will for only File or DB or whatever else you have added).

If you want to follow a completely generic approach, a little technical approach is to have the implementing class-name in the properties-file. Like:

STORE_CLASS_NAME = com.mycompany.store.FileStore

// read the value of STORE_CLASS_NAME from a properties-file into a variable called 'className'

DataStore obj = ( DataStore ) Class.forName ( className ) ; // this is using reflection

This is a more generic way of doing it because you can keep adding more implementations for different kinds of stores, add the classes to the class-path, tweak the properties-file and the same code for the existing component will work. But you have a slightly more technical properties-file (whoever modifies it has to know the class-name). Also, reflection slows down the performance a litle bit. But well, if you do things the best way, you have to compromise somewhere. If you write this code at the start-up of the application then it won't hit the performace much once the objects are created because reflection will be used only once (during start-up) and not after that while operation.
0
g46905Author Commented:
Now I am getting a picture whne exactly a base class is required. I am looking at a base class below and it does have a core class associated to it. Can you please have a look both the classes and let me know why would some one need a core class with similar functionality. Both classes are seperated by '***********'.Thanks for your help.

AppBase class ...................


package com.transport;

import java.io.PrintStream;
import java.text.DateFormat;
import com.transport.log.EventLog;
import com.transport.log.StatusLog;
import com.transport.log.Log;
import com.transport.remote.CommServer;
import com.transport.launch.SystemServerApp;
import com.transport.scheduler.Scheduler;
import com.transport.error.ErrHandler;



public class AppBase implements Debuger, Folderable {
      public final static String NL = System.getProperty("line.separator");
      public final static String FS = System.getProperty("file.separator");
      public final static String programConfigName = "program.cfg";      
      public final static String NONE = "None";
      public final static String SYSTEM_WORD = "SYSTEM_DEFAULT";
      public final static String DEFAULT = "DEFAULT";
      public final static String EMPTY_STRING = "";
      public final static String NOT_YET_IMPLEMENTED = "Not implemented";
      public final static int OUTBOUND = 1;
      public final static int INBOUND = 2;
      
      private final Core core;
/**
 * Insert the method's description here.
 
 */
public AppBase() {
      core = new Core();
      core.err = new ErrHandler(this);
}
/**
 * Insert the method's description here.
 
 * @param b com.midamerican.edi.pgp.BaseEdi
 */
public AppBase(AppBase b) {
      super();
      
      if (b == null) {
            core = new Core();
            core.err = new ErrHandler(this);
            return;
      }
      
      this.core = b.core;
}
/**
 * Insert the method's description here.
 
 */
public TPrintStreamAndLog debugLog() {
      return core.debugLog;
}
/**
 * Insert the method's description here.
 *
 */
public void destroyCore() throws Exception {
      if (core != null) {
            core.destroyCore();
      } else {
            System.out.println("System core not initialized or already destroyed");
      }
}
/**
 * Insert the method's description here.
 *
 */
public ErrHandler errHandler() {
      if (core.err == null)
            printToLog("ErrHandler in AppBase not initialized");
      return core.err;
}
/**
 * Insert the method's description here.
 *
 */
public EventLog eventLog() {
      if (!eventLogInitialized())
            System.out.println("Event Log not initialized");
      return core.eventLog;
}
/**
 * Insert the method's description here.
 *
 */
public boolean eventLogInitialized() {
      return core.eventLog != null;
}
/**
 * Insert the method's description here.
 *
 */
public static String formatDir(String dir) {
      if (dir.endsWith(FS))
            return dir;
      return dir + FS;
}
/**
 * Insert the method's description here.
 *
 */
public com.transport.alarm.AlarmerDaemon getAlarmer() {
      return getSystemServerApp().getAlarmer();
}
/**
 * Insert the method's description here.
 *
 */
public String getBinDir() {
      return getRootDir() + "bin" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public CommServer getCommServer() {
      return core.commServer;
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getConfigDir() {
      return getRootDir() + "config" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getDbDir() {
      return getRootDir() + "db" + FS;
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getDefaultErrorDir() {
      return getRootParentDir() + "files" + FS + "error" + FS;      
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getDefaultInboxDir() {
      return getRootParentDir() + "files" + FS + "inbound" + FS + "default_inbox" + FS;      
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getDefaultOutboxDir() {
      return getRootParentDir() + "files" + FS + "outbound" + FS + "default_outbox" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getExternalBinDir() {
      return getExternalDir() + "bin" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getExternalClassDir() {
      return getExternalDir() + "classes" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getExternalDir() {
      return getRootParentDir() + "external" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getExternalDocDir() {
      return getExternalDir() + "doc" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getExternalRemoteClassDir() {
      return getExternalDir() + "remote" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getFrontEndDir() {
      return getRootDir() + "frontend" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getGuiConfigDir() {
      return getFrontEndDir() + "config" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getGuiLogsDir() {
      return getFrontEndDir() + "logs" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getHelpDir() {
      return getRootParentDir() + "help" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getImageDir() {
      return getRootDir() + "image" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getLogDir() {
      if (core.logDir != null)
            return core.logDir;
      return getMainLogDir();
}
/**
 * Insert the method's description here.
 *
 */
public String getMainLogDir() {
      return getRootDir() + "logs" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public String getPatternDir() {
      return getRootDir() + "pattern" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public ConfigFile getProgramConfig() throws Exception {
      ConfigFile cf = new ConfigFile(new java.io.File(getConfigDir() + programConfigName));
      cf.setFirstSectionAsCurrent();
      return cf;
}
/**
 * Insert the method's description here.
 *
 */
public String getProjectName() {
      return core.projectName;
}
/**
 * Insert the method's description here.
 *
 */
public java.lang.String getRootDir() {
      if (core.rootDir == null)
            return "Root dir not initialized";
      return core.rootDir;
}
/**
 * Insert the method's description here.
 *
 */
public String getRootParentDir() {
      String r = getRootDir();
      int i = r.lastIndexOf(FS);
      i = r.lastIndexOf(FS, i - 1);
      if (i == -1)
            return("Wrong path in root dir " + r);
      return r.substring(0, i + 1);
}
/**
 * Insert the method's description here.
 *
 */
public Scheduler getScheduler() {
      return core.scheduler;
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getSecurityDir() {
      return getRootDir() + "security" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public Sequence getSequence() {
      return core.sequence;
}
/**
 * Insert the method's description here.
 *
 */
public int getServerPortFromConfig() throws Exception {
      ConfigFile cf = getProgramConfig();
      return cf.getInt("server_port");
}
/**
 * Insert the method's description here.
 *
 */
public java.util.Date getStartDate() {
      return core.startDate;
}
/**
 * Insert the method's description here.
 *
 */
public SystemServerApp getSystemServerApp() {
      return core.systemServerApp;
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getTempDir() {
      return getRootDir() + "temp" + FS;
}
/**
 * Insert the method's description here.
 *
 * @return java.lang.String
 */
public java.lang.String getTmpConfigDir() {
      return getRootDir() + "tmp" + FS + "config" + FS;
}
/**
 * Insert the method's description here.
 *
 */
public void initBase() throws Exception {
      if (core.initialized)
            throw new Exception("Core already initialized");

      if (core.rootDir == null)
            initRootDir();

      ConfigFile cf = getProgramConfig();
      core.sequence = new Sequence(this, getRootDir());
      core.debug = new DebugLevel(cf.getString("debug"));
      core.logdebug = new DebugLevel(cf.getString("log_debug"));
      initDebugStreams();
      errHandler().init(getLogDir(), cf);
      setStatusLog(new StatusLog(getLogDir(), getDbDir()));
      setEventLog(new EventLog(getLogDir()));
      core.projectName = cf.getString("project_name");
      core.initialized = true;
}
/**
 * Insert the method's description here.
 *
 */
private void initDebugStreams() throws Exception  {
      if (core.debugLog != null)
            core.debugLog.close();

      Log log = core.logdebug.isTrue() ? new Log(getLogDir(), Debuger.DEBUG_LOG_NAME) : null;
            
      setDebugLog(new TPrintStreamAndLog(
            core.debug.isTrue() ? core.systemOut : null,
            log));      
}
/**
 * Insert the method's description here.
 *
public void initRootDir() {
      if (core.rootDir != null)
            return;
            
      setRootDir(Option.getSystemRootDir());
}
/**
 * Insert the method's description here.
 *
 */
public boolean isDebug() {
      return core.debug.isTrue();
}
/**
 * Insert the method's description here.
 *
 */
public final static boolean isDefault(String str) {
      return str != null && str.equals(DEFAULT);
}
/**
 * Insert the method's description here.
 *
 */
public boolean isEmpty(String value) {
      return value == null || value.trim().length() == 0;
}
/**
 * Insert the method's description here.
 *
 */
public final static boolean isNone(String str) {
      return Tools.isNone(str);
}
/**
 * Insert the method's description here.
 *
 */
public void printlnInfo(String msg) {
      if (core.systemOut != null)
            core.systemOut.println(msg);
}
/**
 * Insert the method's description here.
 *
 */
public void printToLog(long level, String msg) {
      if (core.debug.isSet(level))
            core.systemOut.println(msg);
            
      if (core.logdebug.isSet(level) && core.debugLog.getFileLogger() != null)
            core.debugLog.getFileLogger().println(msg);
}
/**
 * Insert the method's description here.
 *
 */
public void printToLog(String msg) {
      System.out.println(msg);
}
/**
 * Insert the method's description here.
 *
 */
public void setCommServer(CommServer serv) {
      core.commServer = serv;
}
/**
 * Insert the method's description here.
 *
 * @param pr java.io.PrintStream
 */
public void setDebugLog(TPrintStreamAndLog pr) {
      core.debugLog = pr;
      System.setOut(pr);
      System.setErr(pr);
}
/**
 * Insert the method's description here.
 *
 */
public void setErrHandler(ErrHandler eh) {
      core.err = eh;
}
/**
 * Insert the method's description here.
 *
 */
public void setEventLog(EventLog newEventLog) {
      core.eventLog = newEventLog;
}
/**
 * Insert the method's description here.
 *
 */
public void setLogDir(String newLogDir) {
      core.logDir = newLogDir;
}
/**
 * Insert the method's description here.
 *
 */
public void setProjectName(String newName) {
      core.projectName = newName;
}
/**
 * Insert the method's description here.
 *
 */
public void setRootDir(String newRootDir) {
      core.rootDir = formatDir(newRootDir);
}
/**
 * Insert the method's description here.
 *
 */
public void setScheduler(Scheduler sched) {
      core.scheduler = sched;
}
/**
 * Insert the method's description here.
 *
 */
public void setStatusLog(StatusLog newStatusLog) {
      core.statusLog = newStatusLog;
}
/**
 * Insert the method's description here.
 *
 */
public void setSystemServerApp(SystemServerApp app) {
      core.systemServerApp = app;
}
/**
 * Insert the method's description here.
 *
 */
public StatusLog statusLog() {
      if (core.statusLog == null)
            System.out.println("Status Log not initialized");
      return core.statusLog;
}
/**
 * Insert the method's description here.
 *
 */
public synchronized void toExternalLog(String str) throws Exception {
      java.io.FileWriter out = new java.io.FileWriter(getLogDir() + com.transport.external.ExternalProcess.LOG_NAME, true);
      out.write("************************************************" + Log.LINESEP);
      out.write("Result from: " + new java.util.Date() + Log.LINESEP + Log.LINESEP);
      out.write(str);
      out.write(Log.LINESEP + Log.LINESEP);
      out.close();
}

/**
 * Insert the method's description here.
 *
 */
public String getExternalConfigDir() {
      return getExternalDir() + "config" + FS;
}
}

***************************************************************************************
Core class .......................


package com.transport;

import com.transport.log.StatusLog;
import com.transport.log.EventLog;
import com.transport.log.Log;
import com.transport.remote.CommServer;
import com.transport.scheduler.Scheduler;
import com.transport.launch.SystemServerApp;
import com.transport.error.ErrHandler;

/**
 * Insert the type's description here.
 *
 */
public class Core {
      // Keeps original output stream
      public java.io.PrintStream systemOut = System.out;
      
      // Keeps original error stream
      public java.io.PrintStream systemErr = System.err;

      // Store and access status database/log
      public StatusLog statusLog = null;

      // Events
      public EventLog eventLog = null;

      // This is now in place of System.out      
      public TPrintStreamAndLog debugLog = null;

      //// Debug log
      //public Log fileDebugLog = null;

      // Error log
      public ErrHandler err = null;

      // Screen debuging level (what to show on the screen)
      public DebugLevel debug = new DebugLevel();

      // File log debuging level (what to write to log)
      public DebugLevel logdebug = new DebugLevel();

      // Stores absolute root directory (transport/app)
      public String rootDir = null;

      // Sequence
      public Sequence sequence = null;

      // Project name (stored in configuration)
      public String projectName = "Unknown";

      // Scheduler process
      public Scheduler scheduler = null;

      // EDX server
      public CommServer commServer = null;

      // Datetime of system start
      public final java.util.Date startDate = new java.util.Date();

      // Application
      public SystemServerApp systemServerApp;

      // Here are temporary values until GUI is separated
      public String logDir;

      public boolean initialized = false;
/**
 * Core constructor comment.
 */
public Core() {
      super();
}
/**
 * Insert the method's description here.
*/
public void destroyCore() throws Exception {
      if (systemOut != null) {
            System.setOut(systemOut);
            systemOut = null;
      }

      if (systemErr != null) {
            System.setOut(systemErr);
            systemErr = null;
      }
      
      if (sequence != null) {
            sequence.close();
            sequence = null;
      }

      if (err != null) {
            err.destroy();
            err = null;
      }
      if (statusLog != null) {
            statusLog.close();
            statusLog = null;
      }
      if (eventLog != null) {
            eventLog.close();
            eventLog = null;
      }      
      if (debugLog != null) {
            debugLog.close();
            debugLog = null;
      }      
}
/**
 * Code to perform when this object is garbage collected.
 *
 * Any exception thrown by a finalize method causes the finalization to
 * halt. But otherwise, it is ignored.
 */
protected void finalize() throws Throwable {
      destroyCore();
      super.finalize();
}
}


Thanks,


0
Mick BarryJava DeveloperCommented:
> let me know why would some one need a core class with similar functionality.

The AppBase class provides the functionality by usinmg the core class
ie. without the core class it would be unable to provide that functionality
0
g46905Author Commented:
>> The AppBase class provides the functionality by usinmg the core class

Can you explain this in detail?

Thanks for your help.
0
CEHJCommented:
It's not really different from having a member variable of type FileReader, say, which would enable AppBase to read a file
0
Mick BarryJava DeveloperCommented:
for example if it want to print something to stdout it uses the core class to do that.

public void printlnInfo(String msg) {
     if (core.systemOut != null)
          core.systemOut.println(msg);
}

could have been implemented differentlyly but thats what they have done :)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEHJCommented:
:-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.