public class Animal{
public String name;
/**
* 父类默认构造方法
*/
public Animal(){
System.out.println("Animal()");
}
protected void desc(){
System.out.println("我的名字叫:"+name);
}
}
public class Dog extends Animal{
}
public class Main {
public static void main(String[] aaa) {
Animal animal = new Animal();
animal.name = "tom";
animal.desc();
// 子类会集成父类的属性+方法
Dog dog = new Dog();
dog.name = "jack";
dog.desc();
}
}
2、构造方法
子类实例化时,先调用父类的默认构造方法,再调用子类的构造方法
public class Animal{
public String name;
/**
* 父类默认构造方法
*/
public Animal(){
System.out.println("Animal()");
}
protected void desc(){
System.out.println("我的名字叫:"+name);
}
}
public class Dog extends Animal{
public Dog() {
System.out.println("Dog()");
}
}
public class Main {
public static void main(String[] aaa) {
// Animal()
// Dog()
// 我的名字叫:jack
Dog dog = new Dog();
dog.name = "jack";
dog.desc();
}
}
public class Animal{
public String name;
public int age;
/**
* 父类默认构造方法
*/
public Animal(){
System.out.println("Animal()");
}
public Animal(int age){
System.out.println("Animal(int age)");
this.age = age;
}
public Animal(String name, int age){
System.out.println("Animal(String name, int age)");
this.name = name;
this.age = age;
}
protected void desc(){
System.out.println("我的名字叫:"+name);
}
}
public class Dog extends Animal{
public Dog() {
System.out.println("Dog()");
}
public Dog(String name) {
// 对super的调用必须是构造器中的第一个语句
// int a = 1;
super(name,12);
this.name = name;
}
}
public class Main {
public static void main(String[] aaa) {
// Animal(String name, int age)
// 我的名字叫:jack
Dog dog1 = new Dog("jack");
dog1.desc();
}
}
public class Animal{
public String name;
/**
* 父类默认构造方法
*/
public Animal(){
System.out.println("Animal()");
}
public void desc(){
System.out.println("我的名字叫:"+name);
}
}
public class Dog extends Animal{
private String name;
public Dog() {
System.out.println("Dog()");
}
public Dog(String name) {
this.name = name;
}
public void desc(){
System.out.println("我的名字叫:"+name);
}
public void test(){
System.out.println(name);
System.out.println(super.name);
desc();
super.desc();
}
}
public class Main {
public static void main(String[] aaa) {
// Animal()
// jack
// null
// 我的名字叫:jack
// 我的名字叫:null
Dog dog1 = new Dog("jack");
dog1.test();
}
}
public class Animal{
private String name;
}
public class Dog extends Animal{
}
public class Main {
public static void main(String[] aaa) {
Dog dog1 = new Dog();
// 报错 name 在 Animal 中是 private 访问控制
dog1.name ="jack";
}
}