0

When declaring an object in Java:

Runtime rt = Runtime.getRuntime();
Process lsProc = rt.exec("who -q");
InputStream in = lsProc.getInputStream();

Why is lsproc not declared this way -> Process lsproc = new Process? How can an object lsproc hold the value of another function?

1
  • That´s what the returntype of a method is there for... Commented Oct 14, 2015 at 8:01

3 Answers 3

2
 Process lsProc = rt.exec("who -q");

That line alone means,

That means the method exec of Runtime Class returning an instance IsProc of type Process.

Look at the source code of exec method

public Process exec(String[] cmdarray, String[] envp, File dir)
609        throws IOException {
610        return new ProcessBuilder(cmdarray)
611            .environment(envp)
612            .directory(dir)
613            .start();
614    }

It's returning the instance of ProcessBuilder which is of type Process, that means Process is an abstract class and ProcessBuilder is it's concrete class.

Now you might encounter a question that how

Process pro = new ProcessBuilder(..); 

is valid, that routes you to read about Polymorphism.

Sign up to request clarification or add additional context in comments.

1 Comment

Process is not an interface. It's an abstract class.
0

The method rt.exec("who -q") can return a reference to an instance of type Process. It might create that instance itself by calling new Process (..) (or actually, since Process is an abstract class, by creating an instance of a sub-class of Process), or it may retrieve it from elsewhere.

Following the chain of calls of the Runtime.exec(String) method leads to this call :

    return new ProcessBuilder(cmdarray)
        .environment(envp)
        .directory(dir)
        .start();

The start method calls ProcessImpl.start which actually creates the Process instance.

10 Comments

but when i try to do this: Process lsproc = new Process why do I get an error?
@user5444075 That's because you cannot instantiate an abstract class. Read my answer fully.
@user5444075 Because Process is an abstract class, so it can't be instantiated. The actual class being instantiated is ProcessImpl.
so this means i have to indirectly initialize the object lsproc am i right?
@user5444075 No. It's a direct way. You are just getting initialized in some other method which returns your actual object
|
0

Because it returns a Process. See here #exec(java.lang.String)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.