According to my latest post about Inheritance in C++, I am going to explain the same in Java. Let’s go:
We have to create class CFurniture in file named CFurniture.java (here is the first difference ) and then:
class CFurniture { private int itsType; // differences between private(in Java) and protected(in C++) public CFurniture() ; public void SetType(int myType) { itsType = myType; } public int GetType() { return itsType; } //as you can see, we have to put public/private in all of the lines, where we are defining constructors/methods/variables
Then we create another class called CTable (CTable.java):
class CTable <strong>extends</strong> CFurniture // difference between ":" (in C++) and "<em>extends</em>" (in Java) { private char itsColor; public CTable() { super(); // now we can inherit } public char GetColor() { return itsColor; } public void SetColor(char color) { itsColor = color; }
In main we have to write:
public class Main { public static void main(String[] args) { CTable Table = new CTable(); Table.SetType(6); System.out.println("This table is " + Table.GetType() + " type!"); } }