Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

extending other class and calling private member

Let’s look at the constructor of the Truckclass - it can access the protected field numberOfWheels and the default field name. However, it cannot access the private field age. We can write:
1
2
3
Truck truck = new Truck();
truck.start();
truck.move();
But the Java compiler will complain if we try to invoke the private method test():
1
truck.test();   // COMPILE ERROR, since private member is not inherited

Open in new window


https://www.codejava.net/java-core/the-java-language/12-rules-and-examples-about-inheritance-in-java


i supposed to put below code in which class Car or Truck or Moveable?


public class Truck extends Car {
    public Truck() {
        numberOfWheels = 8;
        name = "Truck";
        age=10;
    }
    
    Truck truck = new Truck();
    truck.start();
    truck.move();
    
}

Open in new window




or as below

public class Car extends Vehicle {
	String name;
	protected int age;
    //protected int age;
    protected int numberOfWheels = 4;
    
    public void move() {
        System.out.print("Moving by engine...");
    }

	@Override
	public void start() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		
	}
	
	/*Truck truck = new Truck();
	truck.start();
	truck.move();*/
}

Open in new window


below i cannot put as it is interface

public interface Moveable {
    public void start();
 
    public void stop();
 
    public void move();
}

Open in new window


please advise
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial