隐藏,封装和继承
private关键字
封装
封装是面向对象的三大特征之一,将对象的状态信息隐藏在内部,不允许外部程序直接访问对象。
Private关键字
在变量前加 private
可以封装变量,封装后只能在同一个类中修改。
public class Demo1 {
private int G = 10; //封装变量G
}
public class Demo {
public static void main(String[] args) {
Demo1.G = 100; //修改变量G,这时会报错
}
}
报错提示:
翻译过来就是:
要使用方法来赋值:
public class Demo1 {
private int G = 10;
public int SetG(int G){ //在原来的类中写方法
this.G = G ;
return this.G;
}
}
public class Demo {
public static void main(String[] args) {
Demo1 demo1 = new Demo1();
int P = demo1.SetG(1000); //通过方法赋值
System.out.println(P);
}
}
继承
extends
继承是面向对象的三大特征之一
//[修饰符] class 子类名 extends 父类名(){}
重写父类方法
直接添加方法
//父类
public class Person {
String name ;
int age;
public Person(){
}
public Person(String name ,int age){
this.name = name;
this.age = age;
}
public void say(){
System.out.println(name + " say,I`m " + age +" years old" );
}
}
//子类
public class Person1 extends Person{
public void say(){ //这里重写了say的无参方法
System.out.println(name + " no say " );
}
public static void main(String[] args) {
Person1 Qin = new Person1();
Qin.name ="Qin";
Qin.say();
}
}
输出结果:
这样做的问题是会导致继承的类中方法无法使用,就要用super
来代替父类调用:
public class Person1 extends Person{ //子类
public void say(){
super.say();//用super来调用父类的say方法
System.out.println(name + " no say " );
}
public static void main(String[] args) {
Person1 Qin = new Person1();
Qin.name ="Qin";
Qin.say();
}
}
输出结果:
[noway] 如果父类中有构造方法,子类中必须有构造方法,而且必须调用[/noway]
//使用super继承父类的构造方法
//子类
public class Trees extends Tree{
int number ;
public static void main(String[] args) {
Trees Trees = new Trees();
Trees.number = 100 ;
Trees.flower();
}
public Trees (){
System.out.println("子类无参构造");
}
//如果父类中有不带参数的构造方法,子类会自动调用
public Trees (String name ,String kind,int number){
super(name,kind); //注意:父类的构造方法必须要在子类构造方法的第一行
this.number = number;
}
public void flower(){
System.out.println("这是 " + kind + " ,名为 " +name + " ,一共" + number + "棵");
}
}
//父类
public class Tree {
String name = "桃树";
String kind = "果树";
public Tree(){
System.out.println("父类无参构造");
}
public Tree(String name ,String kind){
this.name = name ;
this.kind = kind ;
}
public void flower(){
System.out.println("这是 " + kind + " ,名为 " +name + " .");
}
}
输出结果:
多态
指同样的操作作用于不同的对象,,可以有不同的解释,产生不同的执行结果.
只能调用父类中有的方法
向上转型(向上转型只能调用父类中有的或者父类和子类共有的方法)
class Animal1{
String Name = "Aninal" ;
String Say = "SAYYY";
public Animal1(String name, String say) {
this.Name = name;
this.Say = say;
}
public Animal1() {
}
public void Say(){
System.out.println( " Name: " + Name + " Say: " + Say);
}
}
class Dogs extends Animal1{
public void Say(){
System.out.println( " Say: " + Say + " Name: " + Name );
}
public void Run() {
System.out.println(Name + "Run");
}
}
public class Test {
public static void main(String[] args) {
Dogs Dog = new Dogs();
Dog.Say();
Dogs Dog1 = (Dogs)Dog;
Dog1.Say();
}
}
输出结果:
向下转型(强制转型来调用子类的单独的方法)
public class Test {
public static void main(String[] args) {
Dogs Dog1 = (Dogs)Dog;
Dog1.Say();
}
}
输出结果: